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

484
Visualizações
Why is getAttribute() in js giving error :?

following is the code i wrote. If i change code in for loop to i<len-1 then its working just fine except for last link But if i keep it like i<len, it isn't working for any link.

const allLists = document.querySelectorAll("a:link");
var len = allLists.length;

for (var i = 0; i < len; i++) {
  allLists[i].addEventListener("click", function (e) {
    e.preventDefault();
    const href = allLists[i].getAttribute("href");
    console.log(href);
    if (href == "#") {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    }
  });
}

Error: script.js:33 Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute') at HTMLAnchorElement.

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

0

Because i variable by len after your looping

Then, each time the click event is called, the code to be run will always be:

const href = allLists[len].getAttribute("href");

This problem is a closure problem you can see more here

The revised code will look like : (change var to let)

const allLists = document.querySelectorAll("a:link");
var len = allLists.length;

for (let i = 0; i < len; i++) {
  allLists[i].addEventListener("click", function (e) {
    e.preventDefault();
    const href = allLists[i].getAttribute("href");
    console.log(href);
    if (href == "#") {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    }
  });
}
<a href="1">1</a>
<a href="2">2</a>
<a href="3">3</a>
<a href="4">4</a>

about 4 years ago · Juan Pablo Isaza Relatório

0

As stated in the Mozilla developer docs “ querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results.”

So I would suggest following the docs and code a ‘forEach’ loop instead of a ‘for’ loop.

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