esafwan
esafwan

Reputation: 18059

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>

Upvotes: 30

Views: 160579

Answers (10)

Simon Arnold
Simon Arnold

Reputation: 16177

Pure JavaScript answer:

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

Might help someone someday.

Upvotes: 6

Scott
Scott

Reputation: 21

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

Upvotes: 2

Greg
Greg

Reputation: 617

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');

Upvotes: -1

Nwachukwu A. Nnaemeka
Nwachukwu A. Nnaemeka

Reputation: 369

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

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

Upvotes: 5

Jaykumar Patel
Jaykumar Patel

Reputation: 27624

If Condition to check, currently class active or not

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

Upvotes: 0

andyb
andyb

Reputation: 43823

$('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

Upvotes: 8

a&#39;r
a&#39;r

Reputation: 37029

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')

Upvotes: 8

Johan
Johan

Reputation: 1557

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
}

Upvotes: 9

sushil bharwani
sushil bharwani

Reputation: 30217

use the hasClass jQuery method

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35803

I think you want to use hasClass()

$('li.menu').hasClass('active');

Upvotes: 61

Related Questions