Question

Is the first .on function more efficient than second one ?

$( "div.container" ).on( "click", "p", function(){
});

$( "body" ).on( "click", "p", function(){
});

Regards

Was it helpful?

Solution

From the jQuery documentation itself about jQuery: .on():

jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So, "#myForm", "a.external", and "button" are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $( "body" ).on( "click", "#commentForm .addNew", addComment ) use $( "#commentForm" ).on( "click", ".addNew", addComment ).

OTHER TIPS

The narrower the first selector is, the better the performance is.

But the first example won't work I guess, because you are monitoring all the <p>s container in <p>s having container class, and a <p>cannot contain another <p>, due to being a phrasing content.

Sure, as the browser only has to monitor one paragraph for click events as opposed to the entire page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top