jQuery parent() vs. parents()

The parent() method selects the immediate parent element of the selected element within the DOM tree. In contrast, the parents() method traverses upwards from the selected element, selecting all matching elements along the way, up to the root element of the document. This allows you to capture multiple ancestor elements in a single selection.

jQuery parent() method

The jQuery parent() method traverses a single level up the HTML DOM tree from the selected element. This method offers optional parameters that allow developers to apply additional filters, further refining the traversal to meet specific requirements. These optional parameters provide flexibility and control when navigating and selecting parent elements in the DOM hierarchy.

example
$("p").parent().css({"color": "blue"});
<ul> <li>Red</li> <li><p>Blue</p></li> <li>Green</li> </ul>
run this source code Browser View
  • Red
  • Blue

  • Green
Full Source
<html> <head> <title>jQuery parent() example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").parent().css({"color": "blue"}); }); </script> </head> <body> <ul> <li>Red</li> <li><p>Blue</p></li> <li>Green</li> </ul> </body> </html>

jQuery parents() method

The parents() method is employed to identify all parent elements associated with the selected element. It traverses through all levels of ancestors upwards from the selected element and returns all of these ancestor elements. This functionality allows for the comprehensive selection of multiple parent elements within the DOM hierarchy.

example
$("p").parents().css({"color": "red"});
<ul> <li>Red</li> <li><p style="color:blue;">Blue</p></li> <li>Green</li> </ul>
Full Source
<html> <head> <title>jQuery parents() example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").parents().css({"color": "red"}); }); </script> </head> <body> <ul> <li>Red</li> <li><p style="color:blue;">Blue</p></li> <li>Green</li> </ul> </body> </html>

Conclusion

The parent() method traverses only one level up in the DOM tree from the selected element and returns the immediate parent, while the parents() method traverses all levels upward, returning all ancestor elements related to the selected element. This distinction offers different levels of granularity when selecting parent elements in the DOM hierarchy, providing flexibility for different use cases.