Skip to content
Related Articles

Related Articles

Improve Article

jQuery | parent() & parents() with Examples

  • Last Updated : 13 Feb, 2019

The parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element.
Syntax:

$(selector).parent()

Here selector is the selected elements whose parent need to find.
Parameter: It does not accept any parameter.
Return value: It returns the parent of the selected elements.
jQuery code to show the working of this function:




<html>
  
<head>
    <style>
        .main_div * {
            display: block;
            border: 1px solid green;
            color: green;
            padding: 5px;
            margin: 15px;
        }
    </style>
    <script 
          
    </script>
    <script>
        $(document).ready(function() {
            $("span").parent().css({
                "color": "green",
                "border": "2px solid green"
            });
        });
    </script>
</head>
  
<body>
  
  <div class="main_div">
    <div style="width:500px;">div (Great-Grandparent)
      <ul>This is the grand-parent of the selected span element.!
      <li>This is the parent of the selected span element.!
      <span>This is the span element !!!</span>
      </li>
      </ul>
    </div>
   </div>
</body>
  
</html>

In the above code only the parent element of the selected element is get deep green colour.
Output:

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.
Syntax:

$(selector).parents()

Here selector is the selected element whose all parent need to find.
Parameters: It does not accept any parameter.
Return value: It returns all the parents of the selected element.
jQuery code to show the working of this function:




<html>
  
<head>
    <style>
        .main_body* {
            display: block;
            border: 2px solid green;
            color: green;
            padding: 5px;
            margin: 15px;
        }
    </style>
<script 
</script>
<script>
        $(document).ready(function() {
            $("span").parents().css({
                "color": "green",
                "border": "2px solid green"
            });
        });
    </script>
</head>
  
<body class="main_body">
  <div style="width:500px;">This is the great grand parent of the selected span element.!
   <ul>This is the grand parent of the selected span element.!
   <li>This is the parent of the selected element.!
   <span>This is the selected span element.!</span>
   </li>
   </ul>
   </div>
</body>
  
</html>

In the above code all the parent element of the selected is shown by the deep green color.
Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :