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 trialZach Robinson
8,862 PointsWhy exactly is using an ID selector preferred over a class selector when specificity is needed?
Theoretically, couldn't you use a class selector with a unique name (remembering to not assign anything else with that same class) to achieve the same result as if you would have used an ID selector? As far as I've seen, they do virtually the same thing. Is there some different benefit to using an ID selector, like for debugging purposes?
1 Answer
rydavim
18,814 PointsYou could use a class selector with a unique name. However, I think you've sort of answered part of your question when you said, "(remembering to not assign anything else with that same class)".
Sure, that's fine when you have a 3 page website with maybe 250 lines of code. But what about a much larger site? What about when you're working on updating a site from two years ago? What about when you're using vanilla JavaScript and need to select only that element?
Those are just a couple of things to think about when choosing between classes and ids. Happy coding! :)
Zach Robinson
8,862 PointsZach Robinson
8,862 PointsThat makes perfect sense! Thank you!