0

It's a question about dom manipulation inside functions, I have seen code that create shopping list in MDN, it goes like this:

const list = document.querySelector('ul');
const input = document.querySelector('input');
const button = document.querySelector('button');

button.onclick = function() {
  let myItem = input.value;
  input.value = '';

  const listItem = document.createElement('li');
  const listText = document.createElement('span');
  const listBtn = document.createElement('button');

  listItem.appendChild(listText);
  listText.textContent = myItem;
  listItem.appendChild(listBtn);
  listBtn.textContent = 'Delete';
  list.appendChild(listItem);

  listBtn.onclick = function(e) {
    list.removeChild(listItem);
  }

  input.focus();
}
li {
  margin-bottom: 10px;
}

li button {
  font-size: 8px;
  margin-left: 20px;
  color: #666;
}
<body>
  <h1>My shopping list</h1>
  <div>
    <label for="item">Enter a new item:</label>
    <input type="text" name="item" id="item">
    <button>Add item</button>
  </div>
  <ul></ul>
</body>

Now, what I don't understand is, how it possible to use const a few times in order to create elements, why it doesn't cause an error?

In addition I want to ask, How can I manipulate those element:

Let's say I have created few li elements, if for example I want to change the color of one of them to blue, How can I do that?

When I write the variables names in the console I get this: enter image description here

adiga
  • 34,372
  • 9
  • 61
  • 83
  • These consts only exist inside the function; they stop existing when the function finishes. To manipulate list items you would have to keep an array of them outside the function. You could also just grab them from the DOM but it's always better to keep your own state variables. –  Oct 09 '20 at 09:11
  • those constant are applied to that function scope, they are not available on the window scope – Crocsx Oct 09 '20 at 09:11

0 Answers0