1

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

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

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

Regards

Tukkan
  • 1,574
  • 2
  • 18
  • 33
  • 1
    Probably, since the event won't have to propagate as many times to get to the `p.container` as it will to get to the `body`. – Jason P Dec 17 '13 at 14:10
  • 1
    *"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 )`."* [jQuery Doc](http://api.jquery.com/on/#event-performance) – Karl-André Gagnon Dec 17 '13 at 14:12

3 Answers3

2

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

Abbas
  • 14,186
  • 6
  • 41
  • 72
1

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.

Community
  • 1
  • 1
moonwave99
  • 21,957
  • 3
  • 43
  • 64
1

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

isherwood
  • 58,414
  • 16
  • 114
  • 157