开发者

jQuery check if Attr Class exists?

How do I determine if the .attr('class') exists?

I am using this code:

if(jQuery(this).attr('class') != undefined && jQuery(this).hasClass('mycla开发者_如何转开发ss')) {
  //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>


You can check if an element with any class exists by just calling 'length' on a jquery object.

$('.myclass').length


The return value if the attribute class doesn't exists is null or an empty string.


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");
      }
});​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜