Just curious if there is an established “best way” to target child elements inside of a parent element.
For example, if I want to create a click event on the children of a parent element, which one should be preferred?
a) give the parent element and id and do:
$('ul#parent li').click(function() {});
b) or, instead, give each of the children a class name and target them directly:
$('li.child').click(function() {});
I’m asking because I’m trying to squeeze out every bit of performance I can get in a somewhat large application. Logic would dictate that targeting an id is faster than targeting a classname, but does the parent > child structure negate that advantage and justify targeting by classname instead?
Thanks for any insight.
This would be the fastest option:
Always descend from an ID selector if possible.
However if you have a lot of
<li>elements, it’s cheaper to use.delegate(), like this:With
.delegate()you’re attaching one event handler instead ofn(number of<li>) event handlers, one for each<li>. It works off listening for theclickto bubble up to the<ul>, if startup time is killing you, this is a much better option. It’s a tradeoff of startup time binding lots of handlers vs. the bubble cost (which is a very, very, very small cost). If you have lots of elements, this is almost always a better overall option.