Aleksander Fimreite Aleksander Fimreite - 1 year ago 78
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

is OK, but the
throws an error saying it's not a function!


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


var authors = jQuery("li");

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

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("");

$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("");
$active.css("color", "red");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download