admin管理员组

文章数量:1277885

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?

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?

Share Improve this question asked Jun 15, 2016 at 5:02 Andrés BuitragoAndrés Buitrago 2051 gold badge3 silver badges9 bronze badges 1
  • You can use attr() to get class attribute value and pare with the classname $('#id').attr('class') === 'class1' – Tushar Commented Jun 15, 2016 at 5:31
Add a ment  | 

5 Answers 5

Reset to default 8

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 bining

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

Alternatively you can also simply check

$('#id')[0].className == 'class1'

You can get the list of all classes like this:

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

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

selector below is selecting what you need

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

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

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

本文标签: javascriptCheck if element has only one given classStack Overflow