EmmyS
EmmyS

Reputation: 12138

How do I select an element that has a specific class and any other class?

I have this:

<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 multiple 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 do I select divs that contain one specific class plus ANY other class? I need to select all divs that contain class1 plus any of the other classes, but not the div that only contains class1. And this is just a small sampling; there are several hundred classes in our site's stylesheets, so hard-coding anything is not feasible.

Upvotes: 4

Views: 61

Answers (2)

wless1
wless1

Reputation: 3549

You could do something like this:

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

Upvotes: 4

fracz
fracz

Reputation: 21249

I do not see any only-selectors solution, but you can do something like that:

$(".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 any unnecessary white characters it will work.

Upvotes: 0

Related Questions