Kong
Kong

Reputation: 9576

jQuery Descendant Selector Performance

I have a jQuery selector:

$('#myId span')

Is that really a performance dog vs:

$('#myId').find('span')

The first is obviously a bit cleaner to write and I'd like to stick with that if possible.

Upvotes: 2

Views: 182

Answers (1)

Kai
Kai

Reputation: 9308

Test: http://jsperf.com/descend-from-id-vs-select-and-find/3

$('#myId span') will cause jQuery to parse the string using its Sizzle selector engine, reading it from right-to-left, beginning its search with span.

$('#myId').find('span') will cause jQuery to select #myId immediately (bypassing the step to parse with Sizzle), and then traverse down the DOM, multiple levels, to find all descendants.

So the latter is faster.

You could also try $('#myId').children('span'), which might be even faster in some cases, since it will only descend a single level to find children only (as opposed to find, which keeps going).

Upvotes: 5

Related Questions