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

Example

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

Try it yourself »

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

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 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 siblings 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 arguments.

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, 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