views:

142

answers:

5

Hi,

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?

+2  A: 

The class is an attribute so you can do var classname=$("#dv").attr("class") then you can split it into an array with var array=classname.split(" ");

mck89
i have updated my answer, check plz
Web Logic
Updated the answer
mck89
A: 

use this

alert($('#dv').attr('class'));
Starx
i have updated my answer, check plz
Web Logic
+6  A: 
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"

jAndy
+4  A: 

There are a few ways depending on your objective (do you actually need an array, might be a quicker method!).

To get an array of the classes use .attr() and .split():

$('#dv').attr('class').split(' ') == ['red', 'green', 'blue']

To get the literal string use .attr():

$('#dv').attr('class') == 'red green blue'

To check for a class use .hasClass():

$('#dv').hasClass('red') == true
Nick Craver
+1 for `hasClass`, which is more likely what the OP needs if he's trying to split the class attribute into an array.
Andy E
@Andy E's head - Considering the ID is "dv", and the classes are "red green blue" I wonder if the class attribute is being used used as storage for RGB values?? Either way, +1 since Nick met his normal standard by covering the bases.
patrick dw
+1  A: 

with attr() you can set or retrieve any attribute you want. If you have more then one class you can split the string that attr gives you back with split("separator"). Split gives you back an array. $.each(array, function(i, data){}) allows you to do something for each value in a array. If you put that together this is the result:

$.each( $("#dv").attr("class").split(" "), function(i, data) {
    alert(data)
})

And here a demo with your code: http://jsfiddle.net/Cq5JD/

meo