[jquery] Check if a class `active` exist on element with jquery

Check if a class active exist on an li with a class menu

For example

<li class="menu active">something...</li>

This question is related to jquery class

The answer is


$('li.menu.active')

is the simplest way. This will return all elements with both classes.

Or an already answered jQuery hasClass() - check for more than one class


If Condition to check, currently class active or not

$('#next').click(function(){
    if($('p:last').hasClass('active'){
       $('.active').removeClass();
    }else{
       $('.active').addClass();
    }
});

use the hasClass jQuery method


    if($('selector').hasClass('active')){ }

i think this will check if the selector hasClass active ...


You can use the hasClass method, eg.

$('li.menu').hasClass('active') // true|false

Or if you want to select it in one go, you can use:

$('li.menu.active')

You can retrieve all elements having the 'active' class using the following:

$('.active')

Checking wether or not there are any would, i belief, be with

if($('.active').length > 0)
{
    // code
}

i wrote a helper method to help me go through all my selected elements and remove the active class.

    function removeClassFromElem(classSelect, classToRemove){
      $(classSelect).each(function(){
        var currElem=$(this);
        if(currElem.hasClass(classToRemove)){
          currElem.removeClass(classToRemove);
        }
      });
    }

    //usage
    removeClassFromElem('.someclass', 'active');

Pure JavaScript answer:

document.querySelector('.menu').classList.contains('active');

Might help someone someday.


$(document).ready(function()
{
  changeColor = $(.active).css("color","any color");
  if($(".classname").hasClass('active')) {
  $(this).eq(changeColor);
  }
});