jQuery is wonderful javascript library out there for developers. It has came to an extent that we can say Pre jQuery and Post jQuery era of web. jQuery has simplified DOM Manipulation, events etc.. I completely agree with its quotes saying – Write less and Do More. jQuery been a boon for developers till date.

This post is all about three methods offered by jQuery parent, parents and closest to traverse the DOM. Usually we get confuse with this three methods and don’t use them in proper way. Here is my learnings.

parent(selector) : This returns the one immediate parent of the element. Selector is passed in only required cases, like if we want to check if parent exists for the element or in some other situations. Here is simple example which illustrates the parent method.
HTML

<html lang="en">
  <head>
     <script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
  </head>
  <body>
     <div>
        <a href="//www.blogger.com/blogger.g?blogID=1088239211940261500#" id="anchorTag">Click here</a>
         <br />

      </div>
</body>
</html>

jQuery

$('#anchorTag').parent(); //This would return p, immediate parent of a#anchorTag.
 
parents(selector) : This returns the multiple ancestors. Its not restricted to only one level of parent/ancestors of the element. This is the main difference between the parent and parents method.

In the above HTML Snippet. If i do

$('#anchorTag').parents();        //This would return all the ancestors (p, div, body, html)

//On passing selector it will filter down the matched parent elements by selector

$('#anchorTag').parents('div');   //This would give me only div
 
closest(selector) : It works like parents(), except that it returns only one parent/ancestor. This is ideal for the situation i mentioned earlier. If i want to check for existence of element in the ancestry tree, then i would prefer to use the closest rather than parents as it only target the selector rather than filtering it from all the ancestor elements. Here is example

$('#anchorTag').closest(); //This would give me empty object as we have not mentioned the selector
$('#anchorTag').closest('div'); //This would give me the div.

Hope this post has helped in terms of using the parent, parents and closest methods of jQuery library. Thank you for reading.