jQuery Traversing Ancestors
An ancestor is a parent, grandparent, great-grandparent, and so on in logical connections. jQuery includes handy methods such as parent(), parents(), and parentsUntil() that may be used to navigate up in the DOM tree on a single or several levels to quickly find the parent or other ancestors of an element in the hierarchy.
jQuery parent() Method
The jQuery parent() function is used to get the element's immediate parent. The following example uses the class to highlight the
<ul>, which is the immediate parent element of the
<li> highlight on document ready.
jQuery parents() Method
To find the ancestors of the chosen element, use the jQuery parents() function. The example below will place a border around all of the ancestor elements of the
<li>, which are the
You can optionally pass one or more selectors as parameters to the parents() function to narrow down your search for ancestors. The border will be applied around all the ancestors of the
<li> that are
<div> elements in the following example.
jQuery parentsUntil() Method
The jQuery parentsUntil() function returns all ancestors up to but excluding the element matched by the selection. In a nutshell, it retrieves all ancestor items in a DOM hierarchy between two provided components. The following example will create a border to all ancestor elements of the
<li> except the
<html> element, i.e. apply a border to the