Tuesday, 22 April 2014

jQuery: Difference between parent(), parents() and closest()

HTML

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


      </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.

No comments:

Post a Comment