jQuery Traversal - Siblings

Siblings have the same parent element.

With jQuery, you can traverse the sibling elements of elements in the DOM tree.

Horizontal Traversal in the DOM Tree

There are many useful methods that allow us to traverse horizontally in the DOM tree:

  • 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>:

Example

$("document").ready(function(){
  $("h2").siblings();
});

Try It Yourself

You can also use optional parameters to filter the search for sibling elements.

The following example returns all <p> elements that are siblings of the <h2> element:

Example

$("document").ready(function(){
  $("h2").siblings("p");
});

Try It Yourself

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 element of <h2>:

Example

$("document").ready(function(){
  $("h2").next();
});

Try It Yourself

jQuery nextAll() Method

The nextAll() method returns all following sibling elements of the selected element.

The following example returns all following sibling elements of <h2>:

Example

$("document").ready(function(){
  $("h2").nextAll();
});

Try It Yourself

jQuery nextUntil() Method

The nextUntil() method returns all following sibling elements between two given parameters.

The following example returns all sibling elements between <h2> and <h6> elements:

Example

$("document").ready(function(){
  $("h2").nextUntil("h6");
});

Try It Yourself

jQuery prev(), prevAll(), & prevUntil() Methods

prev(), prevAll(), and prevUntil() methods work in a similar way to the above methods, but in the opposite direction: they return the preceding sibling elements (traverse along the sibling elements backward in the DOM tree instead of forward).

jQuery Traversal Reference Manual

To learn about all jQuery traversal methods, please visit our jQuery Traversal Reference Manual.