How to get class name using jquery
Suppose I have an element like this:
<div id="dv" class="red green blue">Something Here !!</div>
I used this:
alert($('#dv').attr('c开发者_运维知识库lass'));
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?
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"
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
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(" ");
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/
use this
alert($('#dv').attr('class'));
精彩评论