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

207
Visualizações
Uncaught TypeError: Cannot read properties of undefined (reading 'style') array of li
var AddressesList = document.getElementsByTagName("li");
for (var i = 0; i < AddressesList.length; i++){
    var allow = true;
    AddressesList[i].addEventListener("click", function() {
        if (allow == true) {
            AddressesList[i].style.backgroundColor = 'red';
            allow = false;
        }
    })
}

I keep getting the error:

Uncaught TypeError: Cannot read properties of undefined (reading 'style')

I have some idea that referencing an array element inside the event listener returns undefined? Because when I try just printing the array element, I get undefined, but it works outside the event listener. What's the issue and how do I fix it

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

0

Its working this way

var AddressesList = document.getElementsByTagName("li");

for (let i = 0; i < AddressesList.length; i++) {
  const element = AddressesList[i];

  var allow = true;
  element.addEventListener("click", function () {
    if (allow) {
      element.style.backgroundColor = "red";
      allow = false;
    }
  });
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app">
      <ul>
        <li>Inder</li>
        <li>Jane Doe</li>
        <li>John Doe</li>
      </ul>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

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