I have a preloaded page and I am trying to add onclick event to all the nodes with a specific class name. But the function in the onclick should use the element node in it.
var elemArr=document.getElementsByClassName('ABC');
for(var i=0;i<elemArr.length;i++){
elemArr[i].onclick = function()
{
console.log(elemArr[i]); // This is being returned as undefined
// How can I use elemArr[i] here
};
}
I tried
for(var i=0;i<elemArr.length;i++){
printObj=elemArr[i];
elemArr[i].onclick = function()
{
console.log(printObj);
var newObject = jQuery.extend(true, {}, printObj);
console.log(newObject );
};
}
but didn't work.I feel the above won't work anyway. How do I solve this problem..?
ivariable, which by the time your handler is called, will have the value ofelemArr.lengthSee the linked question. Simplest solutionfor(var i=0;i<elemArr.length;i++){ elemArr[i].onclick = (function(index) { return function(e){ console.log(elemArr[index]) } })(i);