Cedric Cedric - 3 months ago 9
Javascript Question

Jquery check for multiple classes (All must be present) in an element

Hi I am trying to check if an element has the classes I am finding ex:

<span class="foo bar me"></span>


I want to check if the
foo
and
me
class is present on that element so I used this:

$('body span').hasClass('me', 'foo')


this foo and me is stored in an array but this one didn't work:

var arrayName = ['me', 'foo'];
$('body span').hasClass(arrayName)


the classes I am finding is dynamic that's why it is stored in an array, how can pass the dynamic array like the this one
'me', 'foo'
to the hasClass function?

Note: the array can have 2-4 values in it.

I had my work here: https://jsfiddle.net/pcbttntk/

Thanks in Advance.

Update:
$('body span').hasClass('me', 'foo')
is not working, thanks to brett and Roko, it only checks the first class passed to it.

Answer

So let's say you have

<span class="me foo bar"></span>

you could do:

var classes = ['me', 'foo'];
console.log( $('span').is("."+classes.join(".")) );   // && (Has all classes)
console.log( $('span').is("."+classes.join(", .")) ); // || (Has Either one of)

or simpler:

var classes = ['.me', '.foo']; // (Notice the `.`)
console.log( $('span').is(classes.join("")) );        // && (Has all classes)
console.log( $('span').is(classes.join(", ")) );      // || (Has Either one of)

To recap, .hasClass('me', 'foo') is basically wrong cause .hasClass() accepts only one argument

Comments