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
Daniel Ridgley
2,298 PointsDifference between Id="" and class=""
Just a quick question to help me get a better understanding.
I understand that the "id" and "class" elements are different but what I don't understand is when I should be using each of these?
I know that the "class" element can be reused as many time as I want, and the "id" can't be reused.
Basically my question is when should I use id and when should I use class?
1 Answer
erdragerdragsson
Courses Plus Student 5,887 PointsAs you said the "class" element can be used how many times you want, but the "id" cannot.
When you work with Html and Css you should use the "class" element, as its more flexible. And if you work with Javascript, you should use "Id" to target certain elements on the page.
for example with the "getElementById('idname')"
Hope this helps!
Kind regards
Erdrag
Daniel Ridgley
2,298 PointsDaniel Ridgley
2,298 PointsThanks for the reply, just wondering is there any reason to use the "id" element over the "class" element in HTML and CSS? other than when working with JavaScript.
erdragerdragsson
Courses Plus Student 5,887 Pointserdragerdragsson
Courses Plus Student 5,887 Pointstheres no problem at all using "id" when working only with HTML and CSS.
But if you you want to target a few elements with a specific selector you should use Classes.
Also, remember that "id" have higher specificity than classes.
so there is basically no right or wrongs here, use whatever you think suits the job. But have these tips in mind when you are using these selectors.
Kind regards
Erdrag.