30

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

For example

<li class="menu active">something...</li>
Hubert Kario
  • 21,314
  • 3
  • 24
  • 44
esafwan
  • 17,311
  • 33
  • 107
  • 166
  • possible duplicate of [Determine if an element has a CSS class with jQuery](http://stackoverflow.com/questions/263232/determine-if-an-element-has-a-css-class-with-jquery) – karim79 Aug 02 '11 at 11:58

10 Answers10

61

I think you want to use hasClass()

$('li.menu').hasClass('active');
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
9

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
}
Johan
  • 1,537
  • 1
  • 11
  • 17
8
$('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

Community
  • 1
  • 1
andyb
  • 43,435
  • 12
  • 121
  • 150
8

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')
a'r
  • 35,921
  • 7
  • 66
  • 67
6

Pure JavaScript answer:

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

Might help someone someday.

Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
5
    if($('selector').hasClass('active')){ }

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

2
$(document).ready(function()
{
  changeColor = $(.active).css("color","any color");
  if($(".classname").hasClass('active')) {
  $(this).eq(changeColor);
  }
});
Scott
  • 21
  • 1
  • 1
    Welcome to Stack Overflow! Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Feb 10 '17 at 12:52
1

use the hasClass jQuery method

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
0

If Condition to check, currently class active or not

$('#next').click(function(){
    if($('p:last').hasClass('active'){
       $('.active').removeClass();
    }else{
       $('.active').addClass();
    }
});
Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
-1

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');
Greg
  • 652
  • 6
  • 7