Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element has only one given class?

How to check (with jQuery) if an element has only one given class?

$(#id).hasClass('class1') returns true if the element has that class and another ones. How can I check if it has only THAT class?

like image 418
Andrés Buitrago Avatar asked Dec 14 '22 05:12

Andrés Buitrago


1 Answers

you can use classList

$('#id')[0].classList

and you check check its length

$('#id')[0].classList.length == 1; //returns true if element has only one class

Now check if only one class is present by combining

$('#id').hasClass('class1') && $('#id')[0].classList.length == 1

Alternatively you can also simply check

$('#id')[0].className == 'class1'
like image 174
gurvinder372 Avatar answered Dec 21 '22 10:12

gurvinder372