May 21, 2010

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”

Answer by Starx

use this

alert($('#dv').attr('class'));

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!