With MVC and jQuery I am making significantly more use of CSS. A question that came to mind is what is the best approach for using Element IDs vs. Classes. If I use Element IDs the selectors in jQuery are shorter. For example:
#imageTag... $('#imageTag')
#searchTag... $('#searchTag')
As an alternative it could be structured with a parent container element.
#searchTool, #classifyTool .tag
In this case selectors such as
$('#searchTool .tag') or $('#classifyTool .tag')
could be used. This approach can be particularly useful when there are multiple instances of a class throughout the page, e.g., .tag. You just change the parent container object.
This is just a simple theoretical example and is not intended to represent real styles, just portray the concept.
So there are two questions:
Is there any impact on performance of either the page/CSS or jQuery assuming there are a large # of styles on a page?
The second approach seems more flexible and maintainable. Thoughts based upon your experiences.
Is there a better alternative approach?
Thanks
The basic rule that you need to keep in mind while using classes and ids in CSS is that, id is used for single elements that appear on the page for only once (e.g. header, footer, menu), whereas class is used for single or multiple elements that appear on the page for once or more than once (e.g. paragraphs, links, ...
Values defined as Important will have the highest priority. Inline CSS has a higher priority than embedded and external CSS. So the final order is: Value defined as Important > Inline >id nesting > id > class nesting > class > tag nesting > tag.
ID's used correctly are faster, but with such a minimal difference vs classes - it's not worth any consideration.
It is not advisable to use IDs as CSS selectors because if another element in the page uses the same/similar style, you would have to write the same CSS again. Even if you don't have more than one element with that style right now, it might come later. Hence it is always advisable to use class.
As for which one to use, use whichever is most appropriate. If you have a search box on your page then using an ID for that would be most appropriate because there's only one search box. Table rows on the other hand will probably be identified by class because there is (or can be) more than one.
Try not to use selectors (in CSS or jQuery) like ".class". You're forcing jQuery or the browser to basically traverse the entire document tree. Most of the time the class will only apply to one kind of tag so specify that (eg "div.class"). That alone can make a huge performance difference (particularly on jQuery with a large document).
The length of the selector should not be a consideration. Performance, readability and maintainability should be.
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