jQuery Traversal -Siblings
Siblings share the same parent element.
With jQuery, you can traverse sideways in the DOM tree to find siblings of an element.
Traversing Horizontally in the DOM Tree
There are many useful methods for traversing the DOM tree horizontally:
- siblings()
- next()
- nextAll()
- nextUntil()
- prev()
- prevAll()
- prevUntil()
jQuery siblings() Method
The siblings() method returns all sibling elements of the selected element.
The following example returns all sibling elements of <h2>:
You can also use an optional parameter to filter the search for sibling elements.
The following example returns all <p> elements that are siblings of <h2>:
jQuery next() Method
The next() method returns the next sibling element of the selected element.
This method returns only one element.
The following example returns the next sibling of <h2>:
jQuery nextAll() Method
The nextAll() method returns all following sibling elements of the selected element.
The following example returns all following siblings of <h2>:
jQuery nextUntil() Method
The nextUntil() method returns all following sibling elements between two given arguments.
The following example returns all sibling elements between <h2> and <h6> elements:
jQuery prev(), prevAll() & prevUntil() Methods
prev(), prevAll(), and prevUntil() methods work in a similar way to the above methods, except that they go in the opposite direction: they return previous sibling elements (traversing the previous siblings of an element in the DOM tree, rather than the following siblings).
Other Extensions