Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEvan Hacker
6,898 PointsWhy not just always use class instead of ID?
I understand that ID is for something you will only use once - and it has more weight than a class. But why not just use class every time? Is there any other reason to use ID? Would it be wrong to use only classes? Thanks
Evan Hacker
6,898 PointsThank you Joe Melon
2 Answers
Daniel Riches
19,847 PointsId's come in handy for other things like automated testing, styling and manipulate the element or traversing the DOM with it. If trying to get a specific element, it's easier when it's unique. It's also less likely to change over time. If you have have to get something that only has a class on it, then you have to use a more specific selector, using things like parent elements. The markup might get changed and then the JS, CSS, Automated Test, etc. would have to be changed as well.
Joseph Lander
Full Stack JavaScript Techdegree Graduate 27,765 PointsI see the convention that class names are used for initial styling and the ids for selecting with JS. They may even use the same name to keep the convention going:
e.g.
<div id="container" class="container" > ... </div>
You also mention only using classes and talk about 'weight'. I picked up the CSS naming convention, BEM, to help with this. In short, it's a structure that helps keep the specificity of all elements as flat as possible to avoid problems selecting. There is a site dedicated to this and many articles on it, this one is a 2min read just to give you an idea https://medium.com/@dannyhuang_75970/what-is-bem-and-why-you-should-use-it-in-your-project-ab37c6d10b79
Joe Melon
589 PointsJoe Melon
589 PointsUsually classes are only used if there are more than one element which will take on the same class. Like (class="buttons") for of course buttons. Then an ID is a unique identifier, so for each button (id="submit-button"), (id="back-button") etc.
You don't have to have an ID for everything but you'll find it useful to target something specifically by using an ID. If you want one button to be red you cannot use class because then all the buttons would be red. Instead you'll go with (id="red-submit-button")