I'm coding a landing page. When should I use an ID for an element instead of a class? I know IDs are only referred to once on a page, while classes are referred to multiple times. I also know using a class is faster than using an ID. When should we use a class over and ID for an element?
Asked
Active
Viewed 41 times
-2
-
_“I know IDs are only referred to once on a page, while classes are referred to multiple times.”_ I think you just answered your own question. – Sebastian Simon Nov 12 '15 at 00:42
-
Possible duplicate of [CSS: div id VS. div class](http://stackoverflow.com/questions/544010/css-div-id-vs-div-class); but also of [Difference between id and class in CSS and when to use it](http://stackoverflow.com/questions/12889362) and [Which method is better? CSS classes or ID's?](http://stackoverflow.com/questions/5171450). Did you research this at all? – Sebastian Simon Nov 12 '15 at 00:46
1 Answers
0
Simply put, ID's are for JavaScript, classes are for styling (CSS). You can use Id's for styling still however, where needed. But in general, you should work towards using CSS classes and re-usable code.
Some people also follow a convention of using ID's for chrome elements on their site. Myself, I use classes for everything to allow for future code re-usability. I can't tell you how many times this has made life easier 6 months down the track. If I need to target something with JavaScript, then I also add an ID.
Performance
JavaScript
Id's are faster than classes when referenced in JavaScript.
CSS
Performance depends on the individual browser rendering engine.
Best Practice
Check out this handy guide on MDN that teaches you to write efficient CSS.

Community
- 1
- 1

Samuel MacLachlan
- 1,736
- 15
- 21
-
1ID's are for javascript? No, ID's are made for the sole purpose of styling with css, Variables are for javascript – Provision Nov 12 '15 at 01:05
-
1ID's are good for JavaScript when you need to interact with the DOM. – Samuel MacLachlan Nov 12 '15 at 01:12