OpuLance
OpuLance

Reputation: 461

Jquery :contains for 2 different string

Hi so I have 2 different product title on different page

<h1 class="productTitle">Arizona Sand</h1>
<h1 class="productTitle">Arizona Sand 3 Squares</h1>

I use the :contains() if it contain that word when I visit the product page

if($(".productTitle:contains('Arizona Sand')").length > 0){
    //Do Stuff;
}

if($(".productTitle:contains('Arizona Sand 3 Squares')").length > 0){
    //Do Stuff;
}

But the problem when I visit the 'Arizona Sand 3 Squares' page it's running both of the if statements. So is there another method of doing this?

Upvotes: 1

Views: 40

Answers (1)

Jordumus
Jordumus

Reputation: 2783

This would solve it:

if($(".productTitle:contains('Arizona Sand 3 Squares')").length > 0){
    //Do Stuff;
}
else if($(".productTitle:contains('Arizona Sand')").length > 0){
    //Do Stuff;
}

the logics behind it: you first check for the most rare situation, and ONLY IF that isn't the case, you check for the more common situation.

This way, it will never take both.

Upvotes: 2

Related Questions