chumkiu chumkiu - 1 year ago 46
Javascript Question

Emulate jQuery "on" with selector in pure javascript

I would emulate in pure javascript the main functionality of jQuery


For example

$(document).on('click','.button',function() {
console.log("jquery onclick");

I thought it was enough make something like this

document.addEventListener('click',function(e) {
if( == 'button2') {
console.log("It works");

However when I have this html structure:

<button class="button2">Hello <span>World</span></button>

my script doesn't works when the click event is triggered on
element, because
. (I ignore for this question the complexity of elements with multiple class, and crossbrowsers compatibility)

The source of jQuery is not simple to read and I don't understand how it works (because the first piece of code, in jQuery, works with my html structure).

I need this method because my html is dynamic, and buttons with this class are created, deleted and re-created many times. I don't want add listeners every times.

I would avoid, if possible, to include jquery library.

So, I can do this?

Here the jsFiddle for testing.


This is actually surprisingly simple. You're on the right track, but it's not quite there.

Here's the functions I use:

window.addEvent = function(elem,type,callback) {
    var evt = function(e) {
        e = e || window.event;
    }, cb = function(e) {return evt(e);};
    if( elem.addEventListener) {
    else if( elem.attachEvent) {
    return elem;
window.findParent = function(child,filter,root) {
    do {
        if( filter(child)) return child;
        if( root && child == root) return false;
    } while(child = child.parentNode);
    return false;
window.hasClass = function(elem,cls) {
    if( !('className' in elem)) return;
    return !!elem.className.match(new RegExp("\\b"+cls+"\\b"));

The window.findParent is central to the whole thing, as you can see when I show you how to attach your desired on listener:

window.addEvent(document.body,"click",function(e) {
    var s = window.findParent(e.srcElement ||,function(elm) {
        return window.hasClass(elm,"button");
    if( s) {
        console.log("It works!");