Traversing with jQuery - Siblings

You can use jQuery to traverse the DOM tree sideways to discover siblings of such a component. Siblings are brought up by the same caregiver.

Sideways Motion inside the DOM Tree

For traversing the DOM tree sideways, jQuery has a number of useful techniques:

siblings()

next()

nextAll()

nextUntil()

prev()

prevAll()

prevUntil()


siblings() method in jQuery

All of the selected element's siblings are brought back by the siblings() method.

All of <h2> siblings are brought back in the given example:

Illustration:

EXAMPLE ❯


An optional parameter can be used to determine the response for siblings.

All siblings of <h2> that are <p> elements are returned in the given description:

Illustration:

EXAMPLE ❯


next() method in jQuery

The selected element's next sibling element is brought back by the next() method.

Next sibling of <h2> is brought back in the given description:

Illustration:

EXAMPLE ❯


nextAll() method in jQuery

The selected element's next sibling element is brought back by the nextAll() method.

Next sibling of <h2> is brought back in the given description:

Illustration:

EXAMPLE ❯


nextUntil() is a method in the jQuery library.

Between two given arguments, the nextUntil() function calculates everything next sibling elements.

The example below comes back all sibling components between a <h2> and a <h6> element:

Illustration:

EXAMPLE ❯


prev(), prevAll(), and prevUntil() methods in jQuery

The prev(), prevAll(), and prevUntil() methods function similarly to the methods described above, but in reverse order: those who return prior sibling components (instead of moving forward, traverse the DOM tree backwards along sibling elements.)