I have 5 buttons and I can not change DOM and can not use id and name attribute and cant use innerHTML and now I need to give output like when I click button 1 it should give a alert like "You click button # 1" and same will continue for all 5 buttons. I want to print the value of i .Now I got stuck as I have two solutions :
HTML Part:
//creating 5 buttons
<button>one</button>
<button>two</button>
<button>three</button>
<button>four</button>
<button>five</button>
1st Solution:
/* here I am always having you clicked element #5*/
var nodes = document.getElementsByTagName('button');//getting references
var counter;
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function() {
alert('You clicked element #' + i);
});
} //which is not working
2nd Solution:
/* here I am getting correct output*/
var nodes = document.getElementsByTagName('button');
var counter;
for (var i = 0; i < nodes.length; i++) {
assignEvent(nodes[i], i);
}
function assignEvent(node, i){
node.addEventListener('click', function(){
alert('You clicked element#' + (i+1));
});
}//this one is working
Now my question is why Solution 2 is working but solution 1 doesn't.. Please help. Why solution 2 is carrying the value of i correctly, while not solution 1.