What is the difference between $.closest() and $.parents() methods in jQuery?


The jQuery closest and parents method is used to set or get the first or all ancestor element, matching the selector. Let's see the difference below:

jQuery closest() method

The closest() method begins with the current element and returns only the first ancestors matching the passed expression. This returned jQuery object has zero or one element.

Example

You can try to run the following code to learn how to work with jQuery closest method −

Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
    display: block;
    border: 2px solid blue;
    color: red;
    padding: 5px;
    margin:10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
    $("span").closest("ol").css({"color": "gray", "border": "5px solid maroon"});
 });
</script>
</head>

<body class="myclass">body
  <div style="width:500px;">div
    <ol>ol - This is the third ancestor
    <ol>ol - This is the second ancestor
    <ol>ol - This is the first ancestor
      <li>li - This is the direct parent element
        <span>demo</span>
      </li>
      </ol>
      </ol>
    </ol>  
  </div>
</body>

jQuery parents() method

The parents() method begins with the parent element and returns all ancestors matching the passed expression. This method is different from closest(), since in this the returned jQuery object has zero or more than one element.

Example

Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
 .myclass * {
    display: block;
    border: 5px solid blue;
    color: red;
    padding: 9px;
    margin: 14px;
 }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $("span").parents().css({"color": "green", "border": "4px solid green"});
  });
</script>
</head>

<body class="myclass">body
  <div style="width:600px;">div
    <ol>ol
      <li>li - This is the direct parent element
        <span>demo</span>
      </li>
    </ol>  
  </div>
</body>

</html>

Updated on: 14-Feb-2020

618 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements