Selecting Child Elements in jQuery

I was recently asked whether it would be ‘better/quicker’ to replace
$('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.

About Jennifer Phillips Campbell

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

1 Response to Selecting Child Elements in jQuery

  1. André Neves says:

    For reference, the equivalent to the top would then be


Leave a Reply

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

You are commenting using your 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 )

Connecting to %s