With the rise of styling libraries and mixed CSS in JS solutions, I've seen increased use of classes, while ID selectors are nearly extinct.
Even when understanding the code structure/context and noticing that the element is clearly unique and used once throughout the whole app, it's often still given a class to access via CSS.
Do you still use ID attributes for unique elements?
Latest comments (29)
Why would we use a class for a unique element?
I'm trying to avoid as much as possible, since eventually it's becomes to a variable on window...
Its ironic but the more classes become popular the more ids become powerful.
Meaning if a CSS framework is based entirely on classes then overriding a style for a certain element without headache is as simple as giving it an id, since id's have priority over classes.
I think I'd has two main usecases:
-The label for attribute
yes and a few more actually
Could you elaborate?
Obviously. IDs are for element identification, which means uniqueness. Classes are for, well, classes of elements. Querying the entire DOM for an element through classes when you can simply use IDs is a waste of time and resources. Just use IDs when you need to target one very specific element; otherwise, when targeting a class of elements, use classes (the names are so self-descriptive, why is it still being discussed?).
Sometimes. Generally, I like
id
for 'hooking' with JS - if it's really just one thing. Case and point,React
is using"#app"
.It depends. When there just happens to be one top menu, class is safer. When it has to be id for some reason, id it is.
I sometimes still do that, e.g. a logo that appears on a navbar is often unique, or the headers in section for a blog post (so that a user can link to specific parts rather than the whole document similar to what MSDN does) If you look at websites created by MS you'll notice that they also still use IDs for styling elements that are guaranteed to be unique.
Yes totally "still" using IDs.
The way this question is presented feels like we should stop using the ID attribute? Does anyone else feel that too?
Some comments may only be visible to logged-in visitors. Sign in to view all comments.