Search code examples
jqueryevent-handlingevent-bubbling

jQuery .on efficiency


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

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

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

Regards


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