ES6 (vanilla Javascript) alternative to jQuery on()

In jQuery one can use the on() method (event delegation) to register an event handler for example on the body tag and match bubbling events. This is a vanilla Javascript way to do the same without jQuery.

To register an event handler on the document root and filter the events for the one we are interested, we can do the following.

document.addEventListener("click", (e) => {
    if (e.target.parentNode.querySelector("a.speciallink") != e.originalTarget){
        return
    }
    e.preventDefault();
    // handle event
});
By @MrTango in
Tags :