Reputation: 14575
I'm never sure what the best (most efficient) way to select an element is.
Lets say I have the following layout (extremely simple example)
<div id="navigation">
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
#navigation ul {}
or assign a class to the UL?navigation ul li{}
or assign a class?#navigation ul li:first-child {}
or assign a class?I appreciate these questions are pretty much the same, but I'm curious when you should use a class and when not to.
Upvotes: 11
Views: 3260
Reputation: 10940
There's no hard and fast answer here.
A general rule of thumb might be to use classes when you want to group certain elements together, treat them the same and using a class is the only means of doing it.
In your last example for instance, there is strictly no need for a class.
But, using a class in example 3 will result in better performance, as the browser will located the relevant items quicker. Traded off against this is a slight reduction in code-legibility.. If you have class names on everything then it becomes harder to read the rest of the markup.
In short, in what you have shown above, what you have written is fine imo.
You should read this article though which covers selector efficiency.
Basically the order of efficiency is as follows:
ID, e.g. #header
Class, e.g. .promo
Type, e.g. div
Adjacent sibling, e.g. h2 + p
Child, e.g. li > ul
Descendant, e.g. ul a
Universal, i.e. *
Attribute, e.g. [type="text"]
Pseudo-classes/-elements, e.g. a:hover
The performance difference between classes and Id's is normally irrelevant.
Going further down the list though, things slow down considerably.
This isn't an argument to add classes and id's everywhere - it just allows you to judge the trade-off between performance and maintainability.
Upvotes: 12
Reputation: 3308
For Javascript usage, I think to is more faster than use native selector, and no class or id.
For more details, I think just testing this theory with complex code ( for see the different time ).
Don't forget the javaScript's faster depends to your browser.
For CSS, a good article is here for more details.
Upvotes: 0
Reputation: 71422
I would think it really depends on how complex the structure underneath the #navigation element will end up being. Referencing everything using the #navigation element is probably OK if it is a simple structure like you have shown, but to me if it is more complex or will have different ul, li elements that will need different behaviors then I would id/class the nested elements.
Upvotes: 0
Reputation: 124
#id should be unique and class shouldn't.
so if you need to add some JS - you need #id, if you just want to style different elements, .class is fine.
Upvotes: 0