Alex
Alex

Reputation: 68070

jQuery selector speed

Is selecting by ID-only (or a single identifier) faster than when adding additional identifiers?

For example

$('#element')

vs

$('#container #element')

or even more specific:

$('body div#container div#element')

?

Upvotes: 3

Views: 334

Answers (4)

Raynos
Raynos

Reputation: 169531

Actually calling

document.getElementById("element");

is fastest.

If you really want a jQuery object then call $(document.getElementById("element"));

Benchmark

Upvotes: 1

Neil
Neil

Reputation: 55422

You should always try to use as few selectors as you can that will correctly identify the element(s) that you wish to process. For instance if element is a unique id (as it should be), then #element will uniquely specify it and anything else will be wasteful, both in parsing and processing overhead. (This goes equally for CSS style rules, of course, although in this case the optimal choice of selectors may be different than when using jQuery.)

Upvotes: 1

Brian Nickel
Brian Nickel

Reputation: 27560

$('#element') should be fastest, followed by $('div'). These map to the native functions document.getElementById and document.getElementsByTagName. Anything more complex has to go through complex scripting and document searching.

On everything but IE6, 7, and 8, $('.class') also map to the new document.getElementsByClassName function as well, but this is slower than the other two and still has to go through Sizzle if the browser doesn't support it.

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 817128

Yes, selecting by ID only should be the fastest, because jQuery (or Sizzle) can directly use getElementById. Otherwise the rest of the selector has to be evaluated as well, right to left.

Upvotes: 5

Related Questions