jquery find element by specific class when element has multiple classes

139,970

Solution 1

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

Solution 2

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").

Solution 3

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

Solution 4

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.

Share:
139,970
chris
Author by

chris

nothing to report currently..

Updated on September 29, 2020

Comments

  • chris
    chris over 3 years

    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
    Bojangles over 12 years
    I'd recommend the first selector over the latter one.
  • Bojangles
    Bojangles over 12 years
    Only the first class="" attribute will be read by the browser, let alone jQuery.
  • Bojangles
    Bojangles over 12 years
    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.
  • Carvell Fenton
    Carvell Fenton over 12 years
    You can also substitute the *= for ^= if you are interested in making sure the element's class "begins with" alert-box rather than just "contains" alert-box.
  • Kevin B
    Kevin B over 12 years
    That's the point I meant to get across with this answer, is it not clear enough?
  • Bojangles
    Bojangles over 12 years
    I just wanted to clarify that jQuery won't actually see any further class=""es due to the browser's HTML parser ignoring them.
  • Shadi
    Shadi over 7 years
    I just posted an example jsfiddle jsfiddle.net/frxyqzw3/2 showing the class* idea