Write jQuery code to highlight the clicked list item

Description: When you click a list item it must get the class active, and the other items must lose it.

Hint:

  • Use $(this), .addClass() and .siblings().removeClass().

HTML of the page

<ul id="menu">
  <li class="active">Home</li>
  <li>About</li>
  <li>Contact</li>
</ul>

Solution

$('#menu li').on('click', function () {
  $(this).addClass('active').siblings().removeClass('active');
});

$('#menu li').eq(2).click();   // click on "Contact"
HTML after the code runs

<ul id="menu">
<li class="">Home</li>
<li>About</li>
<li class="active">Contact</li>
</ul>

How it works

  • $(this) is the clicked item. siblings() are the other items of the same list.
  • After the click on Contact, only that item has the class active.

Read CSS Classes and Siblings.


Learn more about the similar topics:
Tutorials
jQuery Events
jQuery Mouse, Keyboard and Form Events
jQuery Event Delegation
Exercises & Assignments
Write jQuery code to hide a paragraph when a button is clicked
Write jQuery code to highlight the clicked list item
Write jQuery code to remove a list item when it is clicked
Write jQuery code to change the image source when a thumbnail is clicked
Write jQuery code to show the text typed in an input field
Write jQuery code to filter a list while typing in a search box
Write jQuery code to count the clicks of a button
Interview Questions & Answers
What is the on() method in jQuery?
What is the difference between click() and on(‘click’) in jQuery?
What is event bubbling in jQuery and how do you stop it?
What is event.preventDefault() in jQuery?
What is event delegation in jQuery and why is it useful?
What is the difference between bind(), live(), delegate() and on() in jQuery?