Home > Enterprise >  How to remove class from another element and add to another?
How to remove class from another element and add to another?

Time:11-24

need your help! I want to show subcategory menu, based on the index of menu link, i pressed.

For now i come up with this code:

$( ".main-menu-link-container" ).click(function() {
  var index = $( ".main-menu-link-container" ).index( this );
  $ ( ".subcategory-menu-links-wrapper" ).eq(index).addClass ( "show" );
});

But now subcategory containers shows on top of each other. How can i remove class "show" from one div, and add to another, when i click another link? Thank you!

ScreenShot

CodePudding user response:

If there should only be one element with the class .show you could select that class for the removement before adding that class to the new element:

$('.show').removeClass('show');

Would look in your code like this:

$( ".main-menu-link-container" ).click(function() {
  var index = $( ".main-menu-link-container" ).index( this );

  $( ".show" ).removeClass( "show" );
  $( ".subcategory-menu-links-wrapper" ).eq(index).addClass( "show" );
});
  • Related