Home > Web Front-end > CSS Tutorial > How to Highlight Only One List Item at a Time Using jQuery\'s `addClass()` and `removeClass()`?

How to Highlight Only One List Item at a Time Using jQuery\'s `addClass()` and `removeClass()`?

Barbara Streisand
Release: 2024-12-01 01:03:10
Original
722 people have browsed it

How to Highlight Only One List Item at a Time Using jQuery's `addClass()` and `removeClass()`?

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');
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template