Click here to Skip to main content
14,456,165 members
Rate this:
Please Sign up or sign in to vote.
See more:
hello coders in the house, I was trying to add a mouseover event listener to the 3 anchor tag on my HTML code.
but I don't know why the loop seems not to be working.
if I do a[0] or a[1] or a[2] if I mouse over the anchor tag, and inspect element, it works fine. it will add the attribute of id to the tag.
but when I try to loop it and use the index of the loop., which is [i]. I got an error in the console. that the element is undefined.
when I tried to use a while loop, it seems to be an infinite loop without ending, I don't understand whats going on.

What I have tried:

<h2>
  <a href="https://www.facebook.com" class="download-wait" target="_blank" data-href="https://www.google.com">
  click me now
  <a/>
  <a href="https://www.facebook.com" class="download-wait" target="_blank" data-href="https://www.google.com">
  click me now
  <a/>
  <a href="https://www.facebook.com" class="download-wait" target="_blank" data-href="https://www.google.com">
  click me now
  <a/>
  </h2>


 for(var i = 0; i <= document.querySelectorAll(".download-wait").length; i++){
   var a = document.getElementsByClassName("download-wait");
a[i].addEventListener("mouseover", function() {
  a[i].id = "download";
})
}


var i = 0;
while(i <= document.querySelectorAll(".download-wait").length){
  var a = document.getElementsByClassName("download-wait");
a[i].addEventListener("mouseover", function() {
 a[i].id = "download";
 i++;
});
}
Posted
Updated 15-Feb-20 3:14am
Comments
Richard MacCutchan 15-Feb-20 5:22am
   
"I got an error"
Then please update your question and show the exact error message, and the line of code that it refers to. Please do not expect people to guess what you see.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You're trying to loop over the wrong thing. Try something like this instead:
var i = 0;
var a = document.getElementsByClassName("download-wait");
for (var i = 0; i < a.length; i++) {
  a[i].addEventListener("mouseover", function() { a[i].id = "download"; });
}
In other words, you needed to be iterating over the elements you returned from getElementsByClassName instead.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100