Consider a simple JS event of
document.getElementsByClassName('test')[0].onclick=function(){
document.getElementsByClassName('test')[0].innerHTML = 'New Text';
}
How can I extend this code to generally work for all elements with class="test". I mean getting the element clicked and replace its content. In fact, we need to get the node number (provided inside the bracket) from the click event.
I am trying to better understand Javascript in unobtrusive codes, not a practical method like jQuery.
Just iterate over them:
I used
(function(i) { return function() { ... }; })(i)instead of justfunction() { ... }because if you happen to useiin the callback, the value ofiwill beelements.length - 1by the time you call it. To fix it, you must shadowiand make it essentially pass by value.