peacecoder peacecoder - 1 year ago 84
jQuery Question

How do I select an element with multiple classes in order

I want to select all the elements that have two classes, a and b, in that order.

<element class="a b">

When I use $(".a + .b") I get elements with both classes in either order. I need only those elements with class = "a b" and not class = "b a". I have the same problem when I use javascript's getElementsByClassName.

Note: The reason I have to specify the order is that some of the divs in my document have class = "a b" and some have "b a" . . . I only want to select those with "a b". The document is not structured elegantly but that's not in my control.

Answer Source

If those elements have no other classes, you can select them by attribute

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

There's also the attributes-starts-with, and -ends-with selector, and the attribute-contains selector, that would pick up the elements even if they did have more classes

$('[class*="a b"]')

note : this would also match ...class="what a bad idea"

Plain JS supports the attribute selectors in querySelector[All]

But this is a bad idea, it shouldn't matter what order the classes are in, and if it does, you're doing something wrong.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download