Home > OS >  How to delete a class with Jquery from an html menu
How to delete a class with Jquery from an html menu

Time:05-11

With Jquery I added the "current" class to all the divs that have the menu_item class. This way I can highlight the menu text when I'm on the current page. However, the first menu item always takes the "current" class even when I'm not on the account page. The problem is that the structure of my pages is composed in such a way that account is always present, I give an example:

mywebsite.com/account - This is where the dashboard is located

mywebsite.com/account/impostazioni - Here are the settings

Since account is always present even if they are on a different page, obviously the script always highlights the first menu item because the word account is present in the link. Is there a way to remove the current class from the first menu item when I'm on a different page but it contains the word account ?

Sorry but I'm new, I don't know Jquery and Js well. Before posting I looked at the Jquery documentation and searched on stacks, but found nothing useful for me. Any reply is appreciated, thanks.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
      
    if(window.location.href.indexOf("/account/") > -1) {
   $(".menu_item.1").addClass('current');
}

    if(window.location.href.indexOf("/ordini/") > -1) {
   $(".menu_item.2").addClass('current');
} 
  });
</script>

<div >
<div >
 <div >
  <a href="/account">
   <i ></i>
   <span >First Item</span>
  </a>
 </div>

 <div >
  <a href="/ordini">
   <i ></i>
   <span >Second Item</span>
  </a>
 </div>
</div>
</div>

CodePudding user response:

You tagged javascript in your question so there is vanilla javascript solutions

  1. if you want to remove specific class use:

element.classList.remove('classname');

  1. if you want to remove all classes class attribute use:

element.removeAttribute('class');

And my advice will be that if you are newbie first start with vanilla javascript and only then when you feel comfortable with start learning libraries (or don't start )))

CodePudding user response:

I found a solution on my own.

basically I inserted another line to remove the class from the first element.

$(document).ready(function() {
   
    if(window.location.href.indexOf("account") > -1) {
   $(".menu_item.1").addClass('current');
} 

    if(window.location.href.indexOf("ordini") > -1) {
   $(".menu_item.2").addClass('current');
   $(".menu_item.1").removeClass('current'); //I add this line
}   

  });
  • Related