5

I want to select an elements parent and it's siblings. However, choosing the .parent().siblings() does not include the original elment's parent.

$(this).parent().siblings().removeClass("active"); 

How can I select the parent's siblings and the parent itself too?

isherwood
  • 58,414
  • 16
  • 114
  • 157
ink
  • 223
  • 5
  • 13

1 Answers1

7

Use jQuery's addBack() method:

$(this).parent().siblings().addBack().removeClass("active");

This selects an element's siblings, and itself, so that you can remove the class.

If you're using a jQuery version less than 1.8, use andSelf() instead.

Update: I've added an example below to show exactly what this method will do.

$('.active a').click(function(){
  $(this).parent().siblings().addBack().removeClass("active");
});
.active {background: yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="active">I'm active. <a href="#">Remove all active</a></div>
<div class="active">I'm active. <a href="#">Remove all active</a></div>
<div class="active">I'm active. <a href="#">Remove all active</a></div>
<div class="active">I'm active. <a href="#">Remove all active</a></div>
<div class="active">I'm active. <a href="#">Remove all active</a></div>
Wes Foster
  • 8,770
  • 5
  • 42
  • 62