Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectors in CSS & jQuery: just the class/id, or the tag as well?

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?

like image 320
stefmikhail Avatar asked Sep 14 '11 18:09

stefmikhail


People also ask

What is the selector in CSS?

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.

What is a selector?

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.


1 Answers

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 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.

like image 130
Jason Gennaro Avatar answered Sep 27 '22 23:09

Jason Gennaro