What is the difference between jQuery.children( ) and jQuery.siblings( ) in jQuery?

jQueryWeb DevelopmentFront End Technology

jQuery children() method
The children( [selector] ) method gets a set of elements containing all of the unique immediate children of each of the matched set of elements.

Here is the description of all the parameters used by this method −

  • selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected.

Example

You can try to run the following code to learn how to work with jQuery children() method:

Live Demo

<html>
   <head>
      <title>jQuery children() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    
      <script>
         $(document).ready(function(){
            $("div").children(".selected").addClass("blue");
         });
      </script>    
      <style>
         .blue {
            color:blue;
         }
      </style>
   </head>
   <body>
   
      <div>
         <span>Hello</span>
         <p class = "selected">Hello Again</p>
         <div class = "selected">And Again</div>
         <p class = "biggest">And One Last Time</p>
      </div>
       
   </body>
</html>

jQuery siblings() method
If you want to get the sibling elements, then use the jQuery siblings() method. It returns all the sibling elements of the selected element.

Example

You can try to run the following code to learn how to work with siblings() method in jQuery:

Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
    display: block;
    border: 2px solid green;
    color: green;
    padding: 3px;
    margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("li.new").siblings().css({"color": "blue", "border": "4px solid blue"});
});
</script>
</head>
<body>

<div style="width:600px;" class="myclass">
  <ol>ol
    <li>li</li>
    <li>li</li>
    <li class="new">li- This is the sibling.</li>
    <li>li</li>
    <li>li</li>
  </ol>  
</div>

</body>
</html>
raja
Published on 16-Dec-2017 18:54:35
Advertisements