How to get class name using jquery
Question by Web Logic
Suppose I have an element like this:
<div id="dv" class="red green blue">Something Here !!</div>
I used this:
alert($('#dv').attr('class'));
But it gives me all three at the same time, I need individually probably stored in an array.
How do I get each of those class names using jquery? Should be simple, right?
Answer by jAndy
var classNames = $('#dv').attr('class').split(' ');
if you just need to know if an element owns a class you might want to use
if( $('#dv').is('.green') ){
alert('its green!');
}
or
if( $('#dv').hasClass('green') ){
alert('its green!');
}
which is a derived function. Keep attention to the different notation
“.className” and just “className”