1
...">

How to choose an element that has a specific class and any other class?

I have it:

<div class="class1 class2">1</div> <div class="class1 class3">2</div> <div class="class1 class4">3</div> <div class="class1">4</div> 

I know if I want to select divs that contain several specific classes, I can do this:

 $('.class1.class2'); 

and if I want to select only divs that contain only one specific class, I can do this:

 $('[.class1]'); 

But how to select divs that contain one particular class plus any other class? I need to select all divs that contain class1 plus any other class, but not a div that contains only class1. And this is just a small sample; There are several hundred classes in our style sheets, so hard coding is not possible.

+4
source share
2 answers

You can do something like this:

 $('.class1').not("[class='class1']") 
+4
source

I don't see a solution for selectors only, but you can do something like this:

 $(".class1").each(function(index, element){ var classes = $(element).attr('class').split(/\s+/); if(classes.length > 1){ // element has other class than class1 } }); 

If your code does not contain extra white characters, it will work.

0
source

All Articles