Search code examples
javascripthtmleventsdomgetelementsbytagname

Wrong variable when looping all element in nodelist


I create a nodelist that selects 2 divs. Then I create a function to show the index of the div that the user clicks. But the output is always be 2. I don't figure out where the mistake is.

This is just a simple problem, but it will solve my other complex problems with many events inside events. Thanks.

HTML:

<div style="background:red; height:50px"></div>
<div style="background:black; height:50px"></div>

Javascript:

var div = document.getElementsByTagName('div');

for (i = 0; i < div.length; i++) {
    div[i].onclick = function() {
        alert(i);
    }
}

Example: https://jsfiddle.net/vutienphat/tm279uot/


Solution

  • Try this:

    In your case, value of i is nothing but a value i has at the end of the loop which is length-1 of node list.

    var div = document.getElementsByTagName('div');
    
    for (i = 0; i < div.length; i++) {
      div[i].onclick = (function(i) {
        return function() {
          alert(i);
        }
      })(i)
    }
    <div style="background:red; height:50px"></div>
    <div style="background:black; height:50px"></div>

    Fiddle here