0

Is there a way to get elements with a class with a CSS attribute selector?

Something like this:

[class.=className]
2
  • from where you get .=? developer.mozilla.org/fr/docs/Web/CSS/… Commented May 19, 2020 at 20:11
  • I used .= in my example because the . matches the . used in class selectors (.className). Commented May 19, 2020 at 20:20

2 Answers 2

2

From MDN:

[attr~=value]

Represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.

So this:

[class~=className]

targets all elements that has the class "className" regardless of whether is has other classes around it.

Sign up to request clarification or add additional context in comments.

2 Comments

But wouldn't it get this element: <p class="text-block">...</p> with this selector: class~=text because "text-block" contains the value "text"? Or would it only select text if it was in a word by itself?
No, that would be how [class*=text] works, because it simply checks if the attribute value contains something. [class~=text] looks for "text" as one word and treats the attribute value as a white-space separated string of words. One of these words must be a complete match.
1

You could use this selector:

[class="className"], [class^="className "], [class$=" className"], [class*=" className "]

It's a bit long because we need to check whether it's just that class, whether it's at the beginning of the class attribute, the end, or in the middle.

1 Comment

Or you could just use [class~=className].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.