Working with class/id selectors in CSS and in jQuery, I often see two distinct approaches:
1. Just the class or id:
CSS:
.foo{}
#bar{}
jQuery:
$(".foo")
$("#bar")
2. The class or id with its tag:
CSS:
div.foo{}
div#bar{}
jQuery:
$("div.foo")
$("div#bar")
My question is: Barring the use of the tag to further refine the selector, is there anything wrong with placing the tag with the class/id? Which is proper syntax?
I’ve heard some that say that unless the tag is needed for specificity, it is dead wrong to place it. While others say it makes no difference, and in fact prefer it as it provides further information concerning the selector.
What do you think?
With the tag included
$("div.foo")ordiv.foo{}you are giving the browser a hand, telling it not to search every element with a certain class or ID. Instead, in the examples above, it would just search
divs.Although the performance may be negligible on a single element or a small page, it could add up if you are talking about a document with thousands of tags and several different css or jQuery calls.
Distinguishing between two elements
In some cases you may need it, too, to distinguish between two elements with the same class.
For Specificity
Plus, I think that you should include the elements when possible, as a way to make your CSS (and jQuery) as specific as possible… keeping the surprises to a minimum!
Better for shared code/troubleshooting/updating
It is also much easier to find/change/edit rules when the element is included in the rule.
EDIT
To respond to @stefmikhail’s comment about @YoTsumi’s benchmark test, here is the difference:
Searching for a unique ID will always be the fastest thing, as there should only be one ID on a page and the engine needs to look for it and it alone. However, as @BoltClock mentioned, there is more to this question than performance.