Aleksander Fimreite Aleksander Fimreite - 9 months ago 40
Javascript Question

jQuery hasClass doesn't work looping through children

I'm trying to look for certain elements if they contain a certain class in a Wordpress Widget. But what I can't understand is why the

authors.hasClass()
is OK, but the
currentAuthor.hasClass()
throws an error saying it's not a function!

HTML

<ul>
<li class="active"></li>
<li></li>
</ul>


JS

var authors = jQuery("li");
authors.hasClass("active");

for (i = 0; i < authors.length; i++) {
var currentAuthor = authors[i];
currentAuthor.hasClass("active");
}

Answer Source

By looping through the objects as an array, youre looking at them as standard JavaScript objects. Because hasClass() is a jQuery method, it can only be used on jQuery objects. You can use jQuery's .each() instead, where jQuery(this) refers to the current element in the loop.

var authors = jQuery("li");

authors.each(function() {
    if (jQuery(this).hasClass("active")){
        //Do stuff
    }
});

That being said, why select all the li elements and then check if they have the active class, when you can simply just select all active elements?

var $active = jQuery("li.active");

$active.each(function() {
    //Do stuff
});

Or depending on what you're doing, you may not even need each()

// Turn all active li elements red
var $active = jQuery("li.active");
$active.css("color", "red");