Choose a parent and all his siblings

I want to select a parent and its siblings. However, choosing .parent().siblings() does not include the original elment parent.

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

How can I choose the parent brothers and the parent himself?

+5
source share
1 answer

Use jQuery addBack() method:

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

This selects the siblings element itself, so you can remove the class.

If you are using jQuery version less than 1.8, use andSelf() instead.

Refresh . I added an example below to show what exactly 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> 
+7
source

Source: https://habr.com/ru/post/1232115/


All Articles