MitulP91
MitulP91

Reputation: 1335

jQuery Best Practice for DOM traversal

I am currently learning jQuery through CodeSchool.com and they mentioned that it is better to do this:

$(document).ready(function() {
    $(".exampleclass").on('click', 'button', function() {
        //some method
    });
});

rather than:

$(document).ready(function() {
    $(".exampleclass button").on('click', function() {
        //some method
    });
});

They gave no reasoning for why though. As far as I can tell, there seems to be no difference between the two, in fact I find the latter to be easier.

Is there a particular reason that the first code block is more acceptable? Does it run quicker, or have any particular advantage?

Upvotes: 3

Views: 91

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

The main difference is the former is equipped to handle dynamically added buttons also since it follows the event delegation model.

The functional difference is the former attaches a click handler to each button element which is present in the dom at the point of the script execution, where as the later attaches a single handler to the .exampleclass element, when an event occurs within the element and it reaches the exampleclass element via event propagation it tests the target element agains the selector passed in this case button if the test is successful then registered handler is called

Upvotes: 4

Related Questions