Add and Remove a Class on Click Using jQuery
When working with list menu items, it's often desirable to highlight the currently active item by adding a class. However, you may encounter challenges in ensuring only one item has the class at a time.
To address this, use jQuery's addClass() and removeClass() methods. Initially, add the class to the desired starting element, such as 'about-link'. Then, use an event listener on the list item ('menu li') to handle clicks.
Inside the event listener, utilize the siblings() method to remove the class from all other list item elements. This ensures that only the clicked-on element retains the class. However, to start with the 'about-link' active, we need to add an additional line of code:
$('#menu li a').on('click', function(){ $('#menu li a.current').removeClass('current'); $(this).addClass('current'); });
In this modified code, we select the 'a' elements within the list items ('menu li a') to ensure we're targeting the links. We then use the current class as a selector to remove it from any previously active link before adding it to the clicked-on link. This eliminates the need to manually add the class to 'about-link' in the initial JavaScript.
The above is the detailed content of How to Highlight Only One List Item at a Time Using jQuery\'s `addClass()` and `removeClass()`?. For more information, please follow other related articles on the PHP Chinese website!