Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('myclass')) {
  //Do something
}

It doesn't seem to work.

like image 516
Tom Avatar asked Jul 28 '11 12:07

Tom


People also ask

How do you check if data attribute exists in jQuery?

The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .

How do you check class is exists in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

What is ATTR jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.


5 Answers

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'))...
like image 198
Abraham Avatar answered Oct 06 '22 15:10

Abraham


Try this..

if(jQuery('#id1').attr('class') =="") {
       alert($('#id1').attr('class'));
  }

<div id="id1">test</div>

like image 35
Manikandan Thangaraj Avatar answered Oct 06 '22 15:10

Manikandan Thangaraj


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

$('.myclass').length
like image 44
mdskinner Avatar answered Oct 06 '22 16:10

mdskinner


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

like image 44
Reporter Avatar answered Oct 06 '22 15:10

Reporter


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");
      }
});​
like image 37
Joseph Marikle Avatar answered Oct 06 '22 16:10

Joseph Marikle