george george - 6 months ago 6
HTML Question

How to add class to list item and remove it from previous item

I need add class

orange
to item list on click and remove it when I click on the next item.

Markup:

<ul class="navbar-custom clearfix">
<li><a href="#start"></a></li>
<li><a href="#description"></a></li>
<li><a href="#syntax"></a></li>
<li><a href="#scrollbar"></a></li>
<li><a href="#rotations"></a></li>
<li><a href="#rotations-rotated"></a></li>
<li><a href="#source"></a></li>
<li><a href="#follow"></a></li>
</ul>


Script:

$("nav").find("li").click(function () {
$(this).toggleClass("orange");
});

Answer

For doing that, toggleClass is not enough,

$("nav").find("li").click(function () {
    //remove all the orange class set with the li elements except the current element
    $("li.orange").not($(this).addClass("orange")).removeClass("orange");
    // add class orange to the current element.
}); 

DEMO