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


7,092 Points

Why use . instead of # for an id selector?

Am i wrong or are we supposed to use #ID for an id selector instead of the .class for a class selector?

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector https://developer.mozilla.org/en-US/docs/Glossary/CSS_Selector

1 Answer

It is equally acceptable to select an element by its id or class name. Both ways are common practice. The difference is that an id can only be used on a single element in a document and is more specific than a class, while a class is less specific but can be used several times.

So it's really up to you on how you want to mark up your document and how you want to go about selecting elements.

Here's a couple practical example for each case:

Selecting by ID: You may chose to select an element by id when you have a single element in your document, for instance, the main logo on a website. You can give the element a unique id of #main-logo. Now when you want to select it with a query selector, you can refer it by it's id and be sure that you are not accidentally picking any other element up, because you know that only that logo has that id.

Selecting by class name: You may chose to select an element by class name when you have multiple elements that you want to share the same classes. For instance, lets say you have multiple buttons throughout your website and you want to be able to select all of them easily. You can give all of those buttons a class of .button and use a query selector by class to make changes to all elements that have the .button class. You couldn't do that with an id, because an id can only be used once.