How to get the class name of an element
I have a collection of divs...
<div class='happy person'><img src='#' /></div>
<div class='fat person'><img src='#' /></div>
<div class='joyous person'><img src='#' /></div>
<div class='grotesque person'><img src='#' /></div>
<div class='sad person'><img src='#' /></div>
that I have selected using...
var people = $('.person')
The results are stored in a class variable. jQuery stores the results of this selection as an array of HTMLDivElements - which they are.
Later on, I want to be able to look at this array and make some decisions with respect to the class of each element. I have read up on a possible solution; but this fails since I am not dealing directly with a jQu开发者_如何学Pythonery object.
How do I get the class names of these divs in the array?
This should work:
var people = $('.person');
$.each(people, function(index, el) {
var _this = $(el);
if (_this.hasClass('happy')) {
alert('Happy!');
} else if (_this.hasClass('fat')) {
alert('Fat!');
}
});
I'm not sure what you mean by "I'm not dealing directly with a jQuery object", as $('.person')
returns a jQuery object, wrapped around an array of elements.
To get the class(es) of an element, just use .attr('class')
on the jQuery object. Combine this with a .map()
and you can create an array of only the class names for each element:
var classes = $('.person').map(function () {
return $(this).attr('class');
}).get();
This will produce the following array:
['happy person', 'fat person', ..., 'sad person']
As taken from: http://bytes.com/topic/javascript/answers/91636-getting-class-name-string, this might be worth trying if you're not using jQuery.
function getClassName(obj) {
if (typeof obj != "object" || obj === null) return false;
return /(\w+)\(/.exec(obj.constructor.toString())[1];
}
To get all of the classes on an individual div, use the .attr
function.
var classes = myDiv.attr('class');
This will return a space-separated list of all the classes on the element.
If you want to check for the existence of a specific class, use .hasClass()
.
var hasJoy = myDiv.hasClass('joyous');
Loop through them using pure JavaScript:
for (var i = 0; i < people.length; i++)
{
var class = people[i].attr('class');
}
Or with jQuery:
people.each(function()
{
var class = $(this).attr('class');
});
You do know that having a class fat person
is not having the class fat person
? It's inheriting the CSS properties from both fat
and person
. If you need a class name like this, use underscores: fat_person
.
div_attrs = node.attributes;
div_class = div_attrs.getNamedItem("class").value;
$(document).click(function(e){
var className = e.target.className;
alert(className);
});
b{
background-color:lightgreen;
padding:10px 20px;
margin:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b class='class-one'>Class One</b>
<b class='class-two'>Class-Two</b>
<b class='class-three'>Class-Three</b>
精彩评论