Home > Back-end >  Newbie addEventListener style CSS change all <li>
Newbie addEventListener style CSS change all <li>

Time:06-29

This is so basic. I'm trying to model various addEventListener scenarios to simply change css style elements.

Here is the html

<ul>
  <li>bullet 1</li>
  <li>bullet 2</li>
</ul>

here is the javascript

const giraffe = document.querySelector("li");

giraffe.addEventListener("click", myFunc);

function myFunc(){
   giraffe.style.backgroundColor = "#f00";
}

I'm trying to understand the behavior.

  • Why does this only work when you click on the first li (nothing happens when you click the second)
  • Why don't all the lis change color when you click on one li

Total newbie. I just about understand arrow functions and can read anonymous functions but I find it easier to follow if you can spell out any extra functions

CodePudding user response:

This is because that the query selector only selects the first occurence that fits the criteria. Consider adding IDs on the HTML elements and select them accordingly.

CodePudding user response:

Although you have more than one of the similar elements, querySelector is only applied to the first element always. It's also the reason why your style only works on giraffe which is the first element.

If you want your click event and style to be applied to all similar elements, you should use querySelectorAll and a loop forEach to change element by element.

const giraffes = document.querySelectorAll("li");

giraffes.forEach(giraffe => giraffe.addEventListener("click", myFunc));

function myFunc(){
   giraffes.forEach(giraffe => giraffe.style.backgroundColor = "#f00");
}
<ul>
  <li>bullet 1</li>
  <li>bullet 2</li>
</ul>

CodePudding user response:

  1. It works on only the first one because that is the behavior of document.querySelector it returns the first element within the document that matches the specified selector, or group of selectors. If you want it to affect all the li elements you should consider using document.querySelectorAll

  2. That's because the click event is attached to just the first li element and this code: giraffe.style.backgroundColor = "#f00"; is changing the background color of just that element.

You can improve your code using the below snippet.

 const lis = document.querySelectorAll('li');
    lis.forEach(li => {
        li.addEventListener('click', () => {
            li.style.backgroundColor = "#f00";
        })
    });
  • Related