1

I am posting my html code for a list:

<ul>
    <li>Notebook</li>
    <li>Jello</li>
    <li>Spinach</li>
    <li>Rice</li>
    <li>Birthday Cake</li>
    <li>Candles</li>
</ul>

I want to apply the following css class on each element of the list:

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

Basically I want to be able to strike it then undo it using toggle. I am able to do it just for the first element of the list. How do I apply for second element and onward since class List. toggle works only with query Selector which selects only the first element of an array. I am a beginner at JavaScript.

norbitrial
  • 14,716
  • 7
  • 32
  • 59
noora
  • 11
  • 7
  • 5
    So how are you doing it? Show that code. So querySelector selects the first element, querySelectorAll matches all the elements – epascarello Oct 25 '19 at 15:20
  • var list= document.querySelector('li'); function upon(){ document.querySelector("li").classList.toggle("done"); } list.addEventListener("click",upon); – noora Oct 25 '19 at 15:52
  • by this method i am able to do it just for first element i.e. notebook. if i use queryselectorAll classList. toggle doesnt work also i cant use an array with addEventListener – noora Oct 25 '19 at 15:53
  • https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return – epascarello Oct 25 '19 at 15:54
  • so it means i have to assign id to all of them and then run the JS code for all of them separately? – noora Oct 25 '19 at 16:12
  • There is no bulk way to update so you select all and loop over it. – epascarello Oct 25 '19 at 16:16
  • tried the loop, still not working. – noora Oct 25 '19 at 16:28
  • cannot figure out a way to jump on to the next element even in the loop. because if i use index [] brackets for iterating to next index element the classList.toggle dont work – noora Oct 25 '19 at 16:30

1 Answers1

0

First of all you have to use querySelectorAll, not just querySelector, since this only selects the first item, as you already noticed ;)

Here is an example that toggles the class when you click on each item:

document.querySelectorAll('li').forEach((listItem) => {
    listItem.addEventListener('click', (event) => {
        event.target.classList.toggle('done');
    });
});
Artur Noetzel
  • 323
  • 1
  • 2
  • 10