Frank Mata
Frank Mata

Reputation: 21

How do I target a looped element by Id with in the same loop?

This is what I'm trying to do:

var numArray = ["One","Two","Three","For","Five","Six"];

for (i = 0, i < numArray.length; i++) {
   document.getElementById('results').innerHTML += <div id='listResult_"+[i]+"'></div><br>;

   var target = document.getElementById('listResult_'+[i]);
   document.addDomListener(target, 'mouseover', function() {
      alert("listResult_"+[i]);
   });
}

It only alerts to the last target Id (listResult_5). How can I target all six individually?

Upvotes: 1

Views: 109

Answers (2)

Quentin
Quentin

Reputation: 943936

Every time you assign anything to innerHTML you destroy the elements in there already. Since you are using += you then create new elements… but the event handler you attached to them has been lost. Create and append elements with standard DOM methods instead.

Additionally, i is a variable. It will be whatever the last value it as assigned was when the loop has finished.

Get the data from context instead.

Your for loop syntax is also incorrect.

addDomListener appears to be a Google Maps feature. Use addEventListener for HTML.

var numArray = ["One","Two","Three","For","Five","Six"];

for (var i = 0; i < numArray.length; i++) {
   var myDiv = document.createElement('div');
   myDiv.id = "listResult_"+[i];
   myDiv.appendChild(document.createTextNode(myDiv.id));
   document.getElementById('results').appendChild(myDiv);
   // Don't append a line break between block containers. Use CSS isntead.
   myDiv.addEventListener('mouseover', function() {
      alert(this.id);
   });
}​

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382806

Try:

for (i = 0, i < numArray.length; i++) {
   document.getElementById('results').innerHTML += "<div id='listResult_"+[i]+"'></div><br>";

   var target = document.getElementById('listResult_'+[i]);    

    (function(e) {
       document.addDomListener(target, 'mouseover', function() {
         alert("listResult_"+[e]);
       });
    })(i);
}

Upvotes: 1

Related Questions