If I add an event listener, should I add it at the document level or further down the document tree?
For example, say I know inputs with class="ExampleCss" are always going to be in a div with id="ExampleDiv". Should I use:
$('#ExampleDiv').on(...);
or
$(document).on(...); ?
Is there a best practice for this I should be aware of?
Thanks in advance.
It’s better to use a more specific selector. When you delegate like this, jQuery has to descend down the DOM tree to find all descendants that match the delegation selector. Obviously
documenthas the most descendants.Using a more specific selector is also clearer and prevents possible mistakes (if you have
.ExampleCssthat you don’t want to trigger this event).The only downside to using the more specific selector is the possibility of having to change the ancestor of the classes that you want to delegate to later.