I only want to select the element if it has one class and that class is 'foobar'.
<style> .foobar { /* only apply to an element if the element has a class and the only class is 'foobar'. */ background: black; color: white; } </style> <div class="foobar">i should be selected</div> <div class="foobar ipsum">i should not be selected</div>
I know I could select it with adding a style for .foobar.ipsum { do one thing } and .foobar { something else } but I don't have control over the additional classes. Basically when the element has only the foobar class, I know it's my element and coming from somewhere else. This is what happens when CSS Library worlds collide. I know that there are deeper issues to resolve here but this is stumping me right now.
To select element that does not have specific class with JavaScript, we can use the document. querySelector method with the :not pseudoclass. const li = document. querySelector("li:not(.
class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.
You can create a selector that will target specific elements with the class applied.
The class selector selects HTML elements with a specific class attribute.
The simplest way with pure CSS is to use an attribute selector:
[class="foobar"] { /* only apply to an element if the element has a class and the only class is 'foobar'. */ background: black; color: white; }
You may not have control over the other elements, but if you have control over yours and you can modify its class
attribute, mayabelle makes a good point about assigning your element its own special class and selecting by that class instead. That way you explicitly state which element is yours rather than going by the assumption that not having additional classes means it's yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With