Easy Tutorial
❮ Sel Input Button Traversing Prevall ❯

jQuery Traversal - Siblings


Siblings share the same parent element.

With jQuery, you can traverse through the siblings of an element in the DOM tree.


Horizontal Traversal in the DOM Tree

There are many useful methods for horizontal traversal in the DOM tree:


jQuery siblings() Method

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

The following example returns all siblings of the <h2> element:

Example

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

You can also use an optional parameter to filter the search for siblings.

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

Example

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

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

Example

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

jQuery nextAll() Method

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

The following example returns all following siblings of the <h2> element:

Example

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

jQuery nextUntil() Method

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

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

Example

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

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

The prev(), prevAll(), and prevUntil() methods work similarly to the methods above, but in the opposite direction: they return the preceding sibling elements (traversing through siblings before the element in the DOM tree, rather than after).

❮ Sel Input Button Traversing Prevall ❯