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 usei
in the callback, the value ofi
will beelements.length - 1
by the time you call it. To fix it, you must shadowi
and make it essentially pass by value.But it's most recommended to use addEventListener (or attachEvent, in IE/Some versions of Opera, I guess):
Just use
this
inside the function.this
will be the element on which the event is being fired.It's a bit more complicated than jQuery's:
But it'll be significantly faster without the bloat that jQuery adds ;)