1

I am trying to toggle each item on a list to change its style through CSS, but I keep getting an error. Can someone explain what is wrong with my code?

HTML

    <button id="enter">Enter</button>
    <ul>
        <li>Notebook</li>
        <li>Apple</li>
        <li>Mango</li>
        <li>Banana</li>
        <li>BlackBerry</li>
        <li>Watermelon</li>
    </ul>

CSS

.change {
  text-decoration: line-through;
}

Javascript

var li = document.querySelectorAll("li");

li.addEventListener("click" , function () {
    li.classList.toggle(".change");
})

Uncaught TypeError: li.addEventListener is not a function

Christopher Bennett
  • 803
  • 1
  • 8
  • 20
Fahad Mir
  • 63
  • 6

1 Answers1

2

You need to loop through all the elements using forEach(). And also remove . before change

var li = document.querySelectorAll("li");

for(let i = 0;i<li.length;i++){
  li[i].addEventListener('click',function(){
    li[i].classList.toggle("change");
  })
}
.change {
  text-decoration: line-through;
}
<button id="enter">Enter</button>
    <ul>
        <li>Notebook</li>
        <li>Apple</li>
        <li>Mango</li>
        <li>Banana</li>
        <li>BlackBerry</li>
        <li>Watermelon</li>
    </ul>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • really good way to do it but i am still new and "this" is still hard to get it but what i understand "this" is li – Fahad Mir Apr 29 '19 at 06:01
  • @FahadMir `this` inside an event handler refers to element on which event is called. It means `this` will be this `
  • ` element which is clicked.
  • – Maheer Ali Apr 29 '19 at 06:02
  • i just to to replace "this" to "li" but get Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLLIElement. can you please wrote it in beginner javascript since i have not good idea about es6 also what does x mean ? i never seen x related stuff – Fahad Mir Apr 29 '19 at 06:09
  • @FahadMir `li` is collection of elements. Its not just one element. You need to loop through it. In the code `li[i]` repesents the single element. I have changed code to simple loops. – Maheer Ali Apr 29 '19 at 06:14