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
menuItems.removeClass('active');
// Add "active" class to the clicked menu li element
$(this).addClass('active');
});
});
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.