Search code examples
javascriptjqueryaddclassremoveclass

jQuery if element has class do something


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" );
  }
});

Solution

  • 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")){
    
    }