murrometz
murrometz

Reputation: 904

What is more effective way to get an element by id - #id or span#id and why?

What is more effective way to get an element by id (if its id is unique)?

#id

or

#div1 #id

or

span#id

and why?

Could you please tell me where I can read about such things? (How to use jQuery selectors faster and more effectively and why exactly so)

Thank you!

Upvotes: 0

Views: 258

Answers (6)

jAndy
jAndy

Reputation: 236092

CSS selectors (aswell as Sizzle, the thing within jQuery which does the query job) work from

right to left

knowing that, you can easily answer the question yourself. Just querying for #id is always the fastest solution. Not only for the reason that more statements after that would be queried first, but also jQuery optimizes this case away for you. That means, just having a selector like #id would directly invoke .getElementById(), which is just the fastest possible DOM operation to get a reference to an element.

However, it's also faster not to be overexplicit in other cases. Thats because of the right to left thing.

Upvotes: 1

Simon Arnold
Simon Arnold

Reputation: 16177

Just the id is better simply because the code have to look for a single element.
See this test that proove it http://jsperf.com/id-vs-tag-id

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86882

#id // most efficient way to get an element by Id in jQuery

id's of HTML elements are suppose to be unique and because of this jQuery will make use of document.getElementById() instead of document.getElementsByTagName() and iterate though the array of elements searching for the correct one.

Upvotes: 2

sharpner
sharpner

Reputation: 3947

#id is the fastest, because it is unique.

I don't know where you can read up on this, but here is a page where you can test and benchmark selectors:

Benchmark selectors

Upvotes: 0

Laurence Burke
Laurence Burke

Reputation: 2358

With jQuery its very easy to just use $("#theId") cause all its looking for is the unique id rather than looking for other conditions such as a parent id

Upvotes: 0

genesis
genesis

Reputation: 50974

#id

Why? Because it doesn't look on another conditions, and in any case, #id should be only one so it doesn't make (in a lot of cases) sense to use span#id

Upvotes: 2

Related Questions