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.
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>
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.