0

I made a simple list items page with JavaScript. And everything works just as expected. What I want is that, every time I add a new list-item, the input field should be cleared. As in the value should be deleted.

function addItem() {

  if (document.querySelector('.text-input').value) {

    const listItem = document.createElement('li');
    listItem.className = 'list-item'
    var input = document.querySelector('.text-input').value;
    listItem.textContent = input;
    document.querySelector('.list').appendChild(listItem);
    document.querySelector('.text-input').value = '';


  }

}

document.getElementById('btn').addEventListener('click', addItem);

And I actually achieved what I wanted with that last line of code in the addItem callback function. However instead of writing document.querySelector('.text-input').value = '';, if I write input = '';, it doesn't work. And this is not making any sense to me cause I declared that variable within that function and also used it for listItem.textContent = input; as you can see.

2
  • 2
    Because this var input = document.querySelector('.text-input').value it's a variable declaration initialized with a value. Doing this input = '' is only re-assigning another value. Probably you're confused about referencing the attribute value. Commented Feb 11, 2018 at 17:46
  • 1
    Please, start write the code in declared variables style. Does not use such "direct" way of coding, because maintain and debug will occurs with a lot of an errors. Commented Feb 11, 2018 at 17:53

1 Answer 1

1

Because this var input = document.querySelector('.text-input').value it's a variable declaration initialized with a value. Doing this input = '' is only re-assigning another value. You're confused about referencing the attribute value.

What you probably want to do is:

const listItem = document.createElement('li');
listItem.className = 'list-item'

var input = document.querySelector('.text-input'); // Get a reference of element text-input

listItem.textContent = input.value; //Use the current value of text-input.
document.querySelector('.list').appendChild(listItem); 

input.value = ''; // Modify the value of the text-input's reference.
Sign up to request clarification or add additional context in comments.

1 Comment

@MagneticKode exactly :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.