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 trial
David Schriever
1,777 Pointswhy use id's?
Hello! I have a question. Why would I use ID's in html? why not just use class for all? Seems the only difference is that IDs can only be used once, so why woulds i add this restriction on myself?
4 Answers
Matt Milburn
20,787 PointsHi David,
You are correct, sir.
- Use classes for styling. Do not apply styles to IDs unless you want to be married to your solutions.
- Use IDs for things like javascript, linking form labels to their inputs, etc.
- Don't let anyone tell you otherwise. It should not be optional.
Emeka Okoye
2,489 PointsIt's always best to use classes to adher to DRY (Don't Repeat Yourself) programming. However, there are times using IDs are useful.
E.g when working with JavaScript or JQuery and you need to get an element by ID.
It's also useful when running content experiments in Google Analytics but you can also use classes for that.
Lastly, certain elements rely on IDs e.g anchor scrolling and working with accordions in twitter bootstrap.
These are all examples but generally when I code a webpage, I only use classes and then I add IDs as and when I need them.
Kallil Belmonte
35,561 PointsHi David, take a look at this article (it explains better than me):
Dom Farnham
19,421 PointsHello David,
There are some situations where you wish to identify and manipulate a paticular element, as opposed to all elements of the same type. For example, you may wish to use JavaScript to add an event handler, like onclick, to a certain button element. Or, you may wish to use CSS to style the button differently to other buttons.
Dom
David Schriever
1,777 PointsDavid Schriever
1,777 PointsThanks Matt, good to be right. :D