jQuery .on efficiency

120 views Asked by At

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

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

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

Regards

3

There are 3 answers

0
Abbas On BEST ANSWER

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 ).

1
moonwave99 On

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.

0
isherwood On

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