How to get current element in getElementsByClassName

前端 未结 3 1825
暗喜
暗喜 2020-12-29 11:23

Consider a simple JS event of

document.getElementsByClassName(\'test\')[0].onclick=function(){
document.getElementsByClassName(\'test\')[0].innerHTML = \'New          


        
3条回答
  •  暖寄归人
    2020-12-29 11:42

    Just use this inside the function. this will be the element on which the event is being fired.

    (function() {
        var elms = document.getElementsByClassName("test"),
            l = elms.length, i;
        for( i=0; i

    It's a bit more complicated than jQuery's:

    $(".test").click(function() {
        $(this).html("New Text");
    });
    

    But it'll be significantly faster without the bloat that jQuery adds ;)

提交回复
热议问题