Srikanth AD
Srikanth AD

Reputation: 1854

jQuery selection performance comparison

Is there a difference in performance between the two jQuery selections mentioned below?

jQuery('#someId') 

versus

jQuery('span#someId')

Note: there is no space between "span" and "#someid"

Also, is there any purpose or advantage of mentioning the type of element like "span" before the ID?

Upvotes: 0

Views: 65

Answers (2)

jQuery('#someId') is eqvivalent to jQuery('span#someId')

As id is unique so better use jQuery('#someId').

id always refers to unique element.


jQuery('#someId') -> element with id someId

jQuery('span#someId') -> Span element with id someId


Performance Result - jsperf

jQuery('#someId') is faster enter image description here


Performance Test of Selectors - jsperf enter image description here


Upvotes: 1

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

Althrough they should be the same, they are not. Putting only the id will alway be faster because jQuery first evaluate the string you pass to determine if it use javascript query selector or id selector. Here the revelant jQuery code.

That beign said, using only an id will always return 1 element while span#id will return every elements.

Check it out here : http://jsfiddle.net/ZW6Ed/

Of course using only the id is faster since getElementById scan the DOM and stop when it find the id while querySelector doesnt.

Why "they should be the same, but they are not"? Because having multiple id is not a valid HTML.

Upvotes: 1

Related Questions