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
Miranda Williams
2,152 PointsWhy use id instead of class?
I've wondered this for a while. An id selector can only be used once on a page, a class selector can be used multiple times. Why use id at all, when class isn't limited in the same way? Does anyone have some unique examples of when using an id would be preferable to using a class?
2 Answers
Stephen Gembar
2,048 PointsThis article helped me when I was starting out and has some very good information.
Stephen O'Connor
22,291 PointsIDs are usually used when you need to reference that element in JavaScript, so if you were looking to fade out a div when a button is clicked the div and button would get IDs instead of classes. So I use IDs for reference and classes for styling ... most of the time.
I'm (almost) sure IDs have more specificity in css than classes do, but don't quote me on that right now ... :)
J.D. Sandifer
18,813 PointsThere are multiple ways to select HTML elements in JavaScript without using ID's. Using jQuery allows for selection by class, tag, and more. In your example, you could use classes like "js-fade-trigger" and "js-fade-out" and reference them from JavaScript using jQuery.
I recommend only using ID's for unique identification of elements on the page when it's required. E.g. "comment-257" on a blog post so people can link directly to that comment when they share it.
I believe you're right about the specificity of ID's, though. Another good reason to avoid using them for styling.
Stephen Gembar
2,048 PointsStephen Gembar
2,048 PointsAlso to what Mr. O'Connor stated ID's and classes mean nothing in css. The only place ID's have more abilities is in the browser.
Miranda Williams
2,152 PointsMiranda Williams
2,152 PointsThis article is great! Thank you so much for the resource. It gave me the larger context that IDs and classes exist within.
J.D. Sandifer
18,813 PointsJ.D. Sandifer
18,813 PointsOne example from that article about when to use an ID: