How can I iterate through a function with for loop? <p>I want to pass the 'y' variable to okayid but there seems to be a problem with the looping. The loop works fine with the first call of 'y' on okay.item(y) but it is not looping through okayid.item(y). It seemed to me like it was a scope problem but I am not sure.</p> <pre><code>var okay = document.getElementsByClassName("Okay"); var okayid = document.getElementsByClassName("OkayID"); var numberOkays = okay.length; for(y = 0; y &lt;= numberOkays; y++){ okay.item(y).onclick = function(){ xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200){ alert('vote Sent to picture with id = ' + okayid.item(y).innerHTML); } }; xmlhttp.open("GET", "ajax/vote.php", true); xmlhttp.send(); }; } </code></pre> <p>Here is the html ...</p> <pre><code>&lt;a class="Link1A Okay" href="#"&gt;&lt;span class="OkayID"&gt;[id]&lt;/span&gt;&lt;div class="Vote1A"&gt;Okay&lt;/div&gt;&lt;/a&gt; </code></pre>