jQuery if element has class do something

11,928

Solution 1

Check with length property or else Use .hasClass() in jquery

$( "#indexHero" ).click(function(){
 if($("#tabNo1.active").length > 0){
   $( "#testID1, #testID2" ).addClass( "hideMe" );
   $( "#testID3" ).removeClass( "hideMe" );
 }
});

or

if($("#tabNo1").hasClass("active")){

}

Solution 2

use hasClass()

   $( "#indexHero" ).click(function(){
      if ($('#tabNo1').hasClass('active')) {
        $( "#testID1, #testID2" ).addClass( "hideMe" );
        //} else {
        $( "#testID3" ).removeClass( "hideMe" );
       }
      }):

Solution 3

Try this:

$( "#indexHero" ).click(function(){
   if($("#tabNo1").hasClass("active"))
   {
      $( "#testID1, #testID2" ).addClass( "hideMe" );
      $( "#testID3" ).removeClass( "hideMe" );
   }
});
Share:
11,928
Jay
Author by

Jay

Web Developer / Software Engineer from the UK. Java Vaadin HTML CSS Bootstrap Javascript jQuery

Updated on July 31, 2022

Comments

  • Jay
    Jay almost 2 years

    I'm trying to toggle whether tabs will be displayed based on whether or not the matched list item has a class of active. I've tried multiple different approaches with if statements and .hasClass but cannot get it to behave as I wish! Any help would be greatly appreciated.

    This is an example of one of my attempts:

    $( "#indexHero" ).onClick(function(){
      $("#tabNo1.active"){
        $( "#testID1, #testID2" ).addClass( "hideMe" );
        $( "#testID3" ).removeClass( "hideMe" );
      }
    });