Andrés Buitrago
Andrés Buitrago

Reputation: 205

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?

Upvotes: 4

Views: 2698

Answers (5)

gurvinder372
gurvinder372

Reputation: 68393

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'

Upvotes: 8

hsh
hsh

Reputation: 1855

You can get the list of all classes like this:

var classList = $('#Id').attr('class').split(/\s+/);
if(classList.length == 1)
   //do something

Upvotes: 2

Mina Jacob
Mina Jacob

Reputation: 1951

selector below is selecting what you need

$('#id[class="desiredClass"]')

check this example http://codepen.io/mozzi/pen/MeeYbQ

Upvotes: 1

brk
brk

Reputation: 50291

With only javascript and classList you can get the number

var _a = document.getElementById("demo");
var _cl = _a.classList.length;
document.write('<pre>'+_cl+'</pre>')

JSFIDDLE

Upvotes: 1

chungtinhlakho
chungtinhlakho

Reputation: 930

$('#footer').attr('class').split(' ').length

Upvotes: 0

Related Questions