When using selectors in CSS and in jQuery, are there any efficiency differences between using'E#id'
and #id
, where E is any HTML element? If yes, does it only apply to certain layout engines and/or Javascript engines?
Asked
Active
Viewed 268 times
4
-
Some of the new (and I mean bleeding-edge new) browsers have CSS performance inspectors that let you test for yourself. – icktoofay Jan 26 '12 at 04:39
-
1In my opinion the only reason to use `'E#id'` is if you only want to select an element with that id _if_ it is of the right type, though I can't really think of many real world examples where there wouldn't be a better way to do it anyway. (Remembering that id should be unique so this should not be used to distinguish between different elements on the same page.) – nnnnnn Jan 26 '12 at 04:51
-
An `id` should only occur once in the document so you shouldn't need the element name part of that selector. – Web_Designer Jan 26 '12 at 04:54
-
Actually `E#id` is considered to be ( if not bad , then ) avoidable practice. As for JQuery, if f care about performance , then instead of `$('#foo')` you should do `document.getElementById('foo')`. – tereško Feb 10 '12 at 12:53
-
The accepted answer is wrong... – BoltClock Dec 24 '12 at 09:28
2 Answers
3
Browsers read the selectors right to left so there is little to be gained by prefixing anything before the id; it is redundant at that point. Source: Writing Efficient CSS from Mozilla
Here's a real world example to test it for yourself. TL:DR; it doesn't seem to matter enough to make a difference.
Relevant further reading from a previous Stack Overflow question
-
2Actually, `E#id` has higher specificity than `#id`. [Demo](http://jsfiddle.net/x7Ahx/) – bookcasey Jan 26 '12 at 05:06
-
1@bookcasey That isn't relevant to the question. The OP is only interested in the speed differences between the two selectors as far as javascript and selector engines are concerned.. – Mark Simpson Feb 10 '12 at 13:19
0
1) It's considered that using ID's for CSS is not a good practice. It should be used when manipulating content through javascript.
2) Over qualifying CSS selector with tag name ul.top-nav or ul#top-nav will only increase overhead on browser since it has to match both the tag & class/ID. Hence, avoid over-qualifying the selector.

Neeraj
- 132
- 7