How to get the class name of an element

I have a collection of div ...

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

which I selected using ...

var people = $('.person')

Results are stored in a class variable. jQuery saves the results of this selection as an array of HTMLDivElements, which they are.

Later I want to be able to look at this array and make some decisions regarding the class of each element. I read about a possible solution; but this fails, since I have no direct relation to the jQuery object.

How to get the class names of these divs in an array?

+3
source share
6 answers

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!');
    }
});
+4
source

, " jQuery", $('.person') jQuery, .

() , .attr('class') jQuery. .map(), :

var classes = $('.person').map(function () {
    return $(this).attr('class');
}).get();

:

['happy person', 'fat person', ..., 'sad person']
+2

: http://bytes.com/topic/javascript/answers/91636-getting-class-name-string, , jQuery.

function getClassName(obj) {
   if (typeof obj != "object" || obj === null) return false;
   return /(\w+)\(/.exec(obj.constructor.toString())[1];
}
+1

JavaScript:

for (var i = 0; i < people.length; i++)
{
  var class = people[i].attr('class');
}

jQuery:

people.each(function()
{
  var class = $(this).attr('class');
});

, fat person fat person? CSS fat person. , , : fat_person.

0

div, .attr.

var classes = myDiv.attr('class');  

This will return a list of all classes in the element, separated by spaces.

If you want to check for a specific class, use .hasClass().

var hasJoy = myDiv.hasClass('joyous');
0
source
div_attrs = node.attributes;
div_class = div_attrs.getNamedItem("class").value;
0
source

Source: https://habr.com/ru/post/1790370/


All Articles