DEV Community

Cover image for Do you still use IDs for unique elements?
Madza
Madza Subscriber

Posted on

Do you still use IDs for unique elements?

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)

Collapse
 
cerchie profile image
Lucia Cerchie

Why would we use a class for a unique element?

Collapse
 
avi_siboni profile image
Avi Siboni

I'm trying to avoid as much as possible, since eventually it's becomes to a variable on window...

Collapse
 
urielbitton profile image
Uriel Bitton

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.

Collapse
 
promikecoder2020 profile image
ProMikeCoder2020

I think I'd has two main usecases:
-The label for attribute

Collapse
 
urielbitton profile image
Uriel Bitton

yes and a few more actually

Collapse
 
promikecoder2020 profile image
ProMikeCoder2020

Could you elaborate?

Collapse
 
joeljuca profile image
Joel JucΓ‘

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?).

Collapse
 
codefinity profile image
Manav Misra

Sometimes. Generally, I like id for 'hooking' with JS - if it's really just one thing. Case and point, React is using "#app".

Collapse
 
galoisgirl profile image
Anna

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.

Collapse
 
hentaichan profile image
γƒ˜γƒ³γ‚Ώγ‚€γ‘γ‚ƒγ‚“

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.

Collapse
 
kibblewhite profile image
kibblewhite • Edited

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.