7

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?

5 Answers 5

14
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"

Sign up to request clarification or add additional context in comments.

Comments

8

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

2 Comments

+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'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.
3

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(" ");

Comments

2

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/

Comments

1

use this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.