Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 434
Cedric Avatar asked Sep 25 '22 13:09

Cedric


1 Answers

Having:

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

Has both me and foo classes:

$('span').is(".foo.me");

Using an array of classes you could use .join() to get the needed string selector ".foo.me" like:

var classes = ['me', 'foo'];
$('span').is("."+ classes.join("."));   

or simpler:

var classes = ['.me', '.foo']; // (Notice the `.`)
$('span').is(classes.join(""));

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

like image 73
Roko C. Buljan Avatar answered Nov 15 '22 05:11

Roko C. Buljan