Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

483
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!