Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

485
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda