jquery find element by specific class when element has multiple classes

chris picture chris · Sep 28, 2011 · Viewed 129.1k times · Source

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?

Answer

John Hartsock picture John Hartsock · Sep 28, 2011

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']");