Everything You Need To Know About jQuery Traversing
Posted By : Ekta Bhadauriya | 29-Apr-2021
We can use Query traversing to find or select HTML elements based on their relation to other elements by choosing one selection and move through that selection until you reach the elements you desire.
The image is given below shows a DOM tree with traversing, you can move up, down, and sideways in the tree, starting from the selected element.
jQuery Traversing - Ancestors
The ancestor could be a parent, grandparent, great-grandparent and to find an ancestor you can use three jQuery methods for traversing up the DOM tree which are:
jQuery parent() Method
Returns only direct parent element of the selected element since it traverses a single level up in the DOM tree.
In the following example the method returns the direct parent element of each <span> elements:
jQuery parents() Method
jQuery parents() method returns all ancestor elements of the selected element up to the document's root element (<html>).
In the following example the method returns all ancestors of all <span> elements:
You can use an optional parameter to search for ancestors.
In the following example the method returns all ancestors of all <span> elements that are <ul> elements:
jQuery parentsUntil() Method
jQuery parentsUntil() Method returns all the ancestor elements between two given elements.
In the following example the method returns all ancestor elements between a <span> and a <div> element:
jQuery Traversing - Descendants
You can use two jQuery methods for traversing down the DOM tree are:
jQuery children() Method
Returns all direct children of the selected element by moving to a single level down in the DOM tree.
In the following example the method returns all elements that are direct children of each <div> elements:
You can use an optional parameter to find the search for children.
In the following example the method returns all <div> elements with the class name "box", that are direct children of <div>:
jQuery find() Method
The find() method returns all the descendant elements of the selected element till the last descendant.
In the following example the method returns all <span> elements that are descendants of <div>:
In the following example the method returns all descendants of <div>: