How to find all the siblings for the clicked element in jQuery?


To find all the siblings for the clicked element in jQuery, use the parent and siblings method, and select the class to find all siblings.

Example

You can try to run the following code to find all the siblings for the clicked element in jQuery:

Live Demo

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".target").click(function(){
     $(this).parent().siblings().removeClass("selectedClass");
     $(this).parent().addClass("selectedClass");
  });
});
</script>
<style>
  a {
      cursor:pointer;
    }
  .selectedClass{
      color:blue;
    }
</style>
</head>
<body>
<h1>Countries</h1>
<ul>
    <li><a class="target">India</a></li>
    <li><a class="target">US</a></li>
    <li><a class="target">UK</a></li>
</ul>
</body>
</html>

Updated on: 17-Dec-2019

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements