Click here to Skip to main content
15,881,139 members

How to addevent listener to three element with the same class on an HTML document

Bill Mayheptad Ritchie asked:

Open original thread
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++;
});
}
Tags: Javascript

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900