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?
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.
A selector is a chain of one or more simple selectors separated by combinators. Combinators are: white space, ">", and "+". White space may appear between a combinator and the simple selectors around it. The elements of the document tree that match a selector are called subjects of the selector.
With the tag included
$("div.foo")
or div.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 div
s.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With