Jonathan
Jonathan

Reputation: 201

jQuery: How to select class that includes two strings

I have images, each with two classes. Here is the relevant portion of the HTML.

class = "thing other0-a"
class = "thing other1-a"
class = "thing other2-a"
class = "thing other3-a"
class = "thing other0-b"
class = "thing other1-b"
class = "thing other2-b"

How can I use jQuery to select classes with "thing" and if it includes "-a"?

I know how to do [class*=-a] but I don't know how to combine selecting for an exact match AND an includes match.

Upvotes: 2

Views: 99

Answers (2)

Frenchy
Frenchy

Reputation: 17037

The equivalent of AND in jQuery:

$("[class*=thing][class*=-a]")

The equivalent of OR in jQuery:

$("[class*=thing],[class*=-a]")

The NOT function :not

$(":not([class*=thing])")  means which doesnt contain "thing"

Upvotes: 3

s.kuznetsov
s.kuznetsov

Reputation: 15223

You can declare two attributes with the desired classes in the selector. Like this:

div[class*=-a][class*=thing]

In this case, the match will be exact.

$('div[class*=-a][class*=thing]').css('color', 'green');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "thing other0-a">text</div>
<div class = "thing other1-a">text</div>
<div class = "thing other2-a">text</div>
<div class = "thing other3-a">text</div>
<div class = "thing other0-b">text</div>
<div class = "thing other1-b">text</div>
<div class = "thing other2-b">text</div>

Upvotes: 2

Related Questions