NicholasByDesign NicholasByDesign - 3 months ago 22
Javascript Question

Vanilla JS version of $(document).on('click', 'foo', function(){});

I have been trying to figure out a good way to replicate the following code as vanilla JS without currying inside a document event listener. What is the way to make the following code below into a vanilla js event listener.

$(document).on('click', 'myElement', function(){
//do something to myElement
});


Is there something like the above that would be similar to the below in theory

document.addEventListener('click', function(event) {
if(event.target){
// do something to myElement
}
});

Answer

Actually what your jquery block does is listening for any click within the document, and when there is a click it checks if the element that was clicked is <myElement>.

You can do the same with a code that is similar to this:

document.addEventListener('click', function(event) {
        if(event.target.nodeName == 'myElement'.toUpperCase()) {
        // do something to myElement
    }
});