Attribute Selector vs Class Selector: Best Practices?

Hi All!

I’m learning Javascript and have been implementing small custom code bits in various projects. I’ve been studying custom code plugins and libraries for Webflow and notice they operate differently.

Memberstack targets elements using attributes, Jetboost targets using class name, and Finsweet components use both classes and attributes.

When developing my own code, I’ve been thinking through the best way to create code that won’t break later. It seems that targeting by class might be susceptible to breaking later if a client unknowingly edits the class name or deletes it.

Attributes on the other hand are hidden in Webflow and require some digging to change, thus making them (seemingly) less susceptible to breaking.

How should I be thinking about this? What are the pros/cons for each approach?


Here is my site Read-Only: LINK
(how to share your site Read-Only link)

And it makes no difference, they’re only ways to target an element.

I have the sensation that you target an element by its class, or ID, or its HTML tag, or a combination of those, as much as you can. If you’re the sole developer, you even create specific classes for targeting, classes that aren’t used for styling.

When you can’t, however, you then try to target by other ways, attributes is one way, using pseudo classes is another. (Like using :nth-child to target the 3rd div from another element.)

Attributes are more likely to change or disappear than classes. Elements can move in the dom, rendering your pseudo class selector obsolete. Prefer classes and IDs.

If you’re the sole maintainer of the code, you don’t really care, efficiency of targeting is the same across methods. Logically speaking, an attribute is for… attributes. It’s just a vocabulary in the end, but it’s supposed to cary a meaning, not to create a selector.

1 Like

Thanks for the explanation, Vincent. This was really helpful and informative.