How do I determine if the .attr('class')
exists?
I am using this code:
if(jQuery(this).attr('class') != undefined && jQuery(this).hasClass('myclass')) {
//Do something
}
It doesn't seem to work.
It depends on what you want. Do you want to check if an element has the class attribute, such as:
<div class></div>
<div class=""></div>
<div class="abc"></div>
If so, use:
if ($('div').attr('class') != undefined)...
If you're trying to check if the element has a specific class, use:
if ($('div').hasClass('abc'))...
Try this..
if(jQuery('#id1').attr('class') =="") { alert($('#id1').attr('class')); }
<div id="id1">test</div>
您可以通过在jquery对象上调用'length'来检查是否存在具有任何类的元素。
$('.myclass').length
如果属性类不存在,则返回值为null或空字符串。
this code works actually: fiddle
HTML:
<div></div>
<div class="myclass"></div>
<div class="blah"></div>
<div></div>
<div class="myclass"></div>
<div class="myclass"></div>
<div></div>
<div class="myclass andAnotherClass"></div>
JS:
$("div").each(function(){
if(jQuery(this).attr('class') != undefined && jQuery(this).hasClass('myclass')) {
jQuery(this).html("I have it");
} else {
jQuery(this).html("I don't have it");
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.