30

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

For example

<li class="menu active">something...</li>
Hubert Kario
  • 19,585
  • 3
  • 22
  • 41
esafwan
  • 16,014
  • 31
  • 104
  • 160
  • 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

59

I think you want to use hasClass()

$('li.menu').hasClass('active');
Richard Dalton
  • 34,863
  • 6
  • 72
  • 90
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,517
  • 1
  • 11
  • 17
7

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
  • 34,325
  • 7
  • 64
  • 65
6

Pure JavaScript answer:

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

Might help someone someday.

Simon Arnold
  • 15,214
  • 6
  • 63
  • 84
6
$('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
  • 42,692
  • 12
  • 119
  • 148
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
  • 28,837
  • 30
  • 92
  • 126
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
  • 25,525
  • 12
  • 68
  • 75
-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
  • 642
  • 6
  • 7