Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select element that contains only the class of "foobar", don't select if it contains any other classes?

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.

like image 410
teewuane Avatar asked Oct 23 '13 16:10

teewuane


People also ask

How do you select an element that does not have a specific class?

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(.

How can we select an element with a specific class in CSS?

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.

Is it possible to make a class selector for a particular element if so how?

You can create a selector that will target specific elements with the class applied.

Which selector will finds elements with a specific class?

The class selector selects HTML elements with a specific class attribute.


1 Answers

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.

like image 190
BoltClock Avatar answered Sep 24 '22 00:09

BoltClock