-1

// I am trying to iterate through the collection of "li" that are returned as result of using the getElementsByTagName method and apply styles to each of them //

let listItems = document.getElementsByTagName('li')[0];
const addItemInput = document.querySelector('input.addItemInput');
const addItemButton = document.querySelector('button.addItemButton');
const removeItemButton = document.querySelector('button.removeItemButton');

listItems.addEventListener('click', () => {
    let count = listItems.length;
    for(let i = 0; i < count; i++) {
      listItems[i].style.textDecoration = "line-through";
      listItems[i].style.color = "gray";
    }


});

addItemButton.addEventListener('click', () => {
  let todoList = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  li.innerHTML = addItemInput.value;
  todoList.appendChild(li);
  addItemInput.value = "";
});

removeItemButton.addEventListener('click', () => {
  let todoList = document.getElementsByTagName('ul')[0];
  let li = document.querySelector('li:first-child');
  todoList.removeChild(li);
});
  • 2
    It's not very clear what you're asking. Where are you trying to iterate the list items? Have you seen the [example](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName#example) on the `getElementsByTagName()` documentation? – Phil Oct 06 '21 at 02:53
  • 1
    You fetch the very first li element from all available li in the DOM with getElementsByTagName. Then you limit your selection to the first occurrence with [0]. I think you took a completely wrong approach. It's also not clear from your question whether you want to style only the clicked one or every li. If you formulate what you have in mind more precisely, I can probably help you. lightItems.length will always 1 if there was at least 1 occurrence. – Hirbod Oct 06 '21 at 02:56

1 Answers1

0

listItems isn't an array; you're immediately indexing (with [0]) the collection that getElementsByTagName returns and storing that single element in the (now misleadingly-named) variable.

More fundamentally, it doesn't look like you're looping in the right place, and probably misworded your question. It looks like you want to be looping over the elements, adding an even listener to each, and have each listener individually re-style the element it's attached to.

However, that probably still won't actually do what you want, because it'll only hook up the listeners once: new elements won't get one, unless:

  1. You add the listener to each new element as you add it. This would work, but there's a better way.
  2. You add an event listener to the parent list (that is, the ul element) and catch the click event as it bubbles. This will require a little more logic inside the event handler, but less elsewhere.
solarshado
  • 567
  • 5
  • 18