Adding an event listener to an element that doesn't exist yet in vanilla javascript

前端 未结 4 2334
我在风中等你
我在风中等你 2021-02-18 16:23

In JQuery I can do:

$(document).on(\"click\",\"a.someBtn\",function(e){
    console.log(\"hi\");
});

to add an event listener to an element th

4条回答
  •  情话喂你
    2021-02-18 17:05

    Use the target property in the event object to get the clicked element. Then, manually test for type/attributes/ids

    document.addEventListener( "click", someListener );
    
    function someListener(event){
        var element = event.target;
        if(element.tagName == 'A' && element.classList.contains("someBtn")){
            console.log("hi");
        }
    }
    

提交回复
热议问题