KulerGary
KulerGary

Reputation: 217

addClass If Any of a Set of Conditions Are Present

I have a series of conditions that if any of them are true (present in the DOM) then I want to addClass to the body. I want to know if there is a simpler or more concise way than what I have ...

if ($('.blog-entry').length > 0) {
    $("body").addClass('stock-plugin');
}
if ($('.contact-form').length > 0) {
    $("body").addClass('stock-plugin');
}

if ($('.fileshare').length > 0) {
    $("body").addClass('stock-plugin');
}

Technically, it works to do it that way, however, I thought that I could do something like this to achieve the same thing, except that it only works on the first condition:

if($('.blog-entry' || '.contact-form' || '.fileshare').length >0 ){
    $("body").addClass('stock-plugin');   
}

What am I doing wrong, or am I trying to hard?

Upvotes: 2

Views: 24

Answers (2)

Phiter
Phiter

Reputation: 14992

This last selector will not work, obviously. This is basically going to pick the first truthy value, in this case '.blog-entry'.

But you can use jQuery selector for multiple classes, like this:

if($('.blog-entry, .contact-form, .fileshare').length > 0 ){
    $("body").addClass('stock-plugin');   
}

You can also use .add(), that will add a new set of elements to the previous selector, like this:

if($('.blog-entry').add('.contact-form').add('.fileshare').length > 0 ){
    $("body").addClass('stock-plugin');   
}

Upvotes: 5

Jim
Jim

Reputation: 3579

jQuery allows you to define more than one selector to look for by separating them with commas:

if($('.blog-entry, .contact-form, .fileshare').length > 0 ){
    $("body").addClass('stock-plugin');   
}

Upvotes: 1

Related Questions