Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
Newbie addEventListener style CSS change all <li>

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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

  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";
        })
    });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda