1

I was trying to add class on a current <a></a> and wanted to remove that active class from other <a></a>. i was trying

MY FIDDLE

HTML

 <ul> <li> <a href="#" class="active"> Home </a> </li> <li> <a href="#"> About </a> </li> <li> <a href="#"> Service </a> </li> </ul> 

jQuery

$('ul li a').click(function(e){ e.preventDefault(); $(this).addClass('active').siblings().removeClass('active'); }); 
4
  • 2
    $(this).addClass('active').parent().siblings().find('a').removeClass('active'); Commented Jul 9, 2016 at 5:05
  • 1
    @PranavCBalan, I feel Invoking 3 methods is little expensive..IMO.. Commented Jul 9, 2016 at 5:07
  • 1
    @Rayon : just an alternative method... :) Commented Jul 9, 2016 at 5:08
  • @PranavCBalan – Yeah.. One-liner ;) Commented Jul 9, 2016 at 5:11

3 Answers 3

2

$('ul li a').click(function(e){ e.preventDefault(); $('ul li a').removeClass('active') $(this).addClass('active'); });
.active{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li> <a href="#" class="active"> Home </a> </li> <li> <a href="#"> About </a> </li> <li> <a href="#"> Service </a> </li> </ul> jQuery

You can remove all the active class from anchor then add the active class to clicked anchor

Sign up to request clarification or add additional context in comments.

Comments

1

a element in your code has no sibling in parent li

Use $('ul li a.active') selector and remove all active classes and then apply active class over current element

$('ul li a').click(function(e) { e.preventDefault(); $('ul li a.active').removeClass('active') $(this).addClass('active'); });
.active { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <ul> <li> <a href="#" class="active"> Home </a> </li> <li> <a href="#"> About </a> </li> <li> <a href="#"> Service </a> </li> </ul>

Comments

0

You need to find the a tag elements which are not the direct sibling but the children of the current a tag element parent siblings.

use the below code to find the a tag elements which are the children of the clicked a tag element's parent li sibling

$(this).addClass('active').parent("li").siblings("li").children("a").removeClass('active'); 

updated fiddle : https://jsfiddle.net/Lwzu738a/1/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.