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.
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 .
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".
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.
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");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With