mrjayviper
mrjayviper

Reputation: 2388

how do I select an element with multiple class?

I've found a similar question but mine is different. Thanks:)

here's the html

<div class="a c h">I'm here1</div>
<div class="a h">I'm here2</div>

I only want to get all elements where class is exactly "a h". I've tried these selector:

$(".a.h")
$(".a.h").not("[class='c']")

but it picks up "a c h" as well.

Any ideas how it can be done? Thanks very much.

Ps. I did search the net but found nothing there.

Upvotes: 1

Views: 50

Answers (3)

David Thomas
David Thomas

Reputation: 253476

If you want only elements with those specific classes (regardless of the order of those classes):

// selects all elements with a class of 'a' and 'h':
$('.a.h').filter(function(){
    // keeps only those elements with only two classes
    // (to avoid having to hard-code the classes that you
    // don't want to 'accidentally' select):
    return this.classList.length === 2;
});

$('.a.h').filter(function() {
  return this.classList.length === 2;
}).css('color', 'red');
div::before {
  content: attr(class);
}
div {
  border: 1px solid #000;
  margin: 0 0 0.5em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a c h"></div>
<div class="a h"></div>
<div class="h a"></div>
<div class="a m h"></div>

If, instead, you want to select only those elements with class a and class h, in that specific order:

$('.a.h').filter(function () {
    return this.className === 'a h';
});

$('.a.h').filter(function() {
  return this.className === 'a h';
}).css('color', 'red');
div::before {
  content: attr(class);
}
div {
  border: 1px solid #000;
  margin: 0 0 0.5em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a c h"></div>
<div class="a h"></div>
<div class="h a"></div>
<div class="a m h"></div>

References:

Upvotes: 1

Nikos M.
Nikos M.

Reputation: 114

$(".a.h").not('.c');

here is the fiddle. https://jsfiddle.net/yrb2m5r1/

Upvotes: 2

Josh Crozier
Josh Crozier

Reputation: 241188

Either use an attribute selector to select the exact value: (example)

$('[class="a h"]')

If the order varies, I guess you could select both variations: (example)

$('[class="a h"], [class="h a"]')

..or just negate elements with a class of .c: (example)

$(".a.h:not(.c)")

Upvotes: 1

Related Questions