Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 jQuery object.

How do I get the class names of these divs in the array?

like image 304
Igbanam Avatar asked Oct 27 '25 12:10

Igbanam


1 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!');
    }
});
like image 60
Shane Garelja Avatar answered Oct 30 '25 02:10

Shane Garelja