Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can add class "Active" on click of an li element and remove it from others at the same time?

Tags:

jquery

css

I am trying to create a menu in which I want to change the CSS of an li element on click while at the same time, CSS of other li's should remain the same.

My menu is:

    <ul id="menu">
    <li><a href="#">Parent 1</a> </li>
    <li><a href="#">item 1</a></li>
    <li><a href="#">non-link item</a></li>
    <li><a href="#">Parent 2</a> </li>
</ul>

and my jquery to add CSS to the selected element is:

 $("#menu li a").click(function() {
    $(this).parent().addClass('selected');

    });

However, right now, I am unable to remove the added CSS from a non-selected element. Is there anyway I can implement this?

like image 256
AppleBud Avatar asked Dec 19 '13 08:12

AppleBud


People also ask

How do you add active class on click event?

click(function() { $('selector. active'). removeClass("active"); $(this). addClass("active"); }); });

How do you add and remove an active class?

removeClass() Method. This method removes one or more class names from the selected elements. If no parameter is specified in the removeClass() method, it will remove all class names from the selected elements.


2 Answers

Try this

$("#menu li a").click(function() {
    $(this).parent().addClass('selected').siblings().removeClass('selected');

    });

DEMO

like image 66
Sridhar R Avatar answered Nov 02 '22 12:11

Sridhar R


Try this

$("#menu li a").click(function() {
  $("#menu li").removeClass('selected');
    $(this).parent().addClass('selected');
});

DEMO

like image 44
Sowmya Avatar answered Nov 02 '22 11:11

Sowmya