Add class active in menu li on click and remove from another li using jquery

To add the "active" class to a menu <li> on click and remove it from other <li> elements using jQuery, you can use the following code:

$(document).ready(function() {
  // Get all menu li elements
  var menuItems = $('.menu li');

  // Add click event handler to menu li elements
  menuItems.on('click', function() {
    // Remove "active" class from all menu li elements
    // Add "active" class to the clicked menu li element

In the code above, .menu is the class assigned to the menu container, and li represents the menu items. Adjust the selector ('.menu li') accordingly based on your specific HTML structure.

When a menu <li> element is clicked, the code removes the "active" class from all menu items using removeClass(). Then, it adds the "active" class to the clicked menu <li> using addClass().

Make sure to include the jQuery library in your HTML file and place this JavaScript code within a <script> tag or an external JavaScript file.

With this code, only the clicked menu item will have the "active" class, while the other menu items will have it removed.

Freelance Website Designer and Developer

Hire Our Website
Designer and Developer

Recent Solutions

Freelance Website Designer and Developer
Indoc Web Design

Copyright © 2024 All rights reserved
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram