37

So I am working on something that wasn't well thought out in the build from the backend team. That leaves me with a document full of divs.

What I am doing is rolling back from the element I need to click on, get the parent container then find an element within the parent which has class="alert-box warn", class="alert-box dead", etc... Essentially, I'm trying to use multiple class selectors on each element. When I try to find just alert-box it doesn't seem to be working right. I'm assuming because it has warn,dead, ``fine, etc...

How can I find just alert-box* or equivalent to a wildcard concept?

Bojangles
  • 99,427
  • 50
  • 170
  • 208
chris
  • 36,115
  • 52
  • 143
  • 252

5 Answers5

74

You can combine selectors like this

$(".alert-box.warn, .alert-box.dead");

Or if you want a wildcard use the attribute-contains selector

$("[class*='alert-box']");

Note: Preferably you would know the element type or tag when using the selectors above. Knowing the tag can make the selector more efficient.

$("div.alert-box.warn, div.alert-box.dead");
$("div[class*='alert-box']");
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
11

You can select elements with multiple classes like so:

$("element.firstClass.anotherClass");

Simply chain the next class onto the first one, without a space (spaces mean "children of").

Bojangles
  • 99,427
  • 50
  • 170
  • 208
5
var divs = $("div[class*='alert-box']");
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
3

An element can have any number of classNames, however, it can only have one class attribute; only the first one will be read by jQuery.

Using the code you posted, $(".alert-box.warn") will work but $(".alert-box.dead") will not.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
0

you are looking for http://api.jquery.com/hasClass/

<div id="mydiv" class="foo bar"></div>

$('#mydiv').hasClass('foo') //returns ture
isJustMe
  • 5,452
  • 2
  • 31
  • 47
  • 5
    No, he's not - he wants to select elements based on which class they have, not to see whether an element he's got has a class or not. – Bojangles Sep 28 '11 at 18:52