5

I'm trying to achieve the equivalent of:

$('div').on('click', function() {
    // Do something
});

But without jQuery. My initial thought was to use a for loop to iterate over all elements in the set, but my guess is there's a better way of achieving this without using a loop (some native method?).

var elems = document.getElementsByTagName('div');

function someEvent() { // Generic function to test against
    alert('event fired');
}

for (var i=0, j = elems.length; i < j; i += 1) {
    elems[i].addEventListener("click", someEvent);
}

Is there a more elegant way of doing this without the inclusion of a library?

2
  • 3
    I think it's either that or binding the event to an parent element that contains all the desired elements (ex. body) and using the target property in the event. Commented Dec 14, 2013 at 5:29
  • You have to loop or delegate, but of course you can write your own wrapper function so that you don't have to repeat looping code all over your scripts every time you need to do this. Note that jQuery's .on() method loops internally. Commented Dec 14, 2013 at 5:35

1 Answer 1

10

What you want is event delegation. It works by binding a single event to a parent of multiple nodes, and analyzing the event's target node. For example, you can bind onmouseup to the body node, and when it is triggered from releasing the mouse on a div node, the body event object will contain that div in the target property. You can analyze the target to make sure it matches certain criterias.

A better way to explain this, is to just provide a working example.

document.body.onmouseup = function (event) {
    var target = event.target || event.toElement;

    if (target.nodeName.toLowerCase() == "div") {
       alert(target.childNodes[0].nodeValue);
    };
};

The main point of interest with this example is the target variable, and the condition to verify that our target is a div. The condition can even be a className or anything your heart desires.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.