Selecting Child Elements in jQuery

I was recently asked whether it would be ‘better/quicker’ to replace
$('ul').children('li').children('a')
with
$('ul li a')

My initial response was to warn that these two lines of code don’t actually do the same thing. As explained in the jQuery API reference for the descendant selector, the suggested replacement would (for example) pick up li elements that were descendants of ul elements – and ‘descendants’ can include grandchildren and so on, not just children.

In this case, the structure of the page meant that this wasn’t an issue. I was surprised, though, to find an article posted earlier this year by Rob Tarr showing that in fact the existing code could be quicker than the suggested replacement. The article, jQuery Selector Performance Testing, shows the results of performance tests of chaining find method calls, chaining children method calls, and chaining selectors. In the tests, chaining the method calls was significantly faster than chaining the selectors.

So in this case the existing code was probably the ‘better/quicker’ option after all.

Advertisements

About Jennifer Phillips Campbell

Software Developer and Medieval Historian
This entry was posted in JavaScript. Bookmark the permalink.

One Response to Selecting Child Elements in jQuery

  1. André Neves says:

    For reference, the equivalent to the top would then be

    $('ul>li>a')

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s