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?
-
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
5 Answers
Reset to default 8you 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
版权声明:本文标题:javascript - Check if element has only one given class? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741303884a2371253.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论