Unchanged global variables after callback excution

Hello

I’m not able to understand the alert box output after I click the example button.
The i variable is updated but the e variable is unchanged.
It seems a very strange behavior!!!

Thanks to all

window.onload=function () {
    var container=document.getElementById("container");
    var elements=container.getElementsByTagName("*");
    var button=document.getElementById("button");
    elements=Array.prototype.slice.call(elements, 0);
    var i=0;
    var e=elements[i];
    button.addEventListener("click", function () {
        alert (e.nodeName+"  "+i)
        /*
        At first click the alert output: DIV 0;
        At second click the alert output: DIV 1;
        At thrird click the alert output: DIV 2;
        ad so on...
        */
        i++;
        })
    }

button id="button" exemple button
div id="container" // container for three following elements div p ul
      div style="width:200px; height:200px; background-color:#111" div       // nested DIV
      p style="width:200px; height:200px; background-color:#111"p        // nested P
      ul style="width:200px; height:200px; background-color:#111"ul       ///nested UL
div

Edit the post, select the text and hit the code button that looks like this < / >

1 Like

not at all. you only increment i, but you never change e.

1 Like

Tank you!!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.