jQuery Traversing - Siblings


With jQuery you can cut through the sides of the DOM tree to find your siblings for something.

The siblings have one parent.


Traversing Sideways in The DOM Tree

There are many useful jQuery methods for traversing sideways in the DOM tree:

  • siblings()
  • next()
  • nextAll()
  • nextUntil()
  • prev()
  • prevAll()
  • prevUntil()

jQuery siblings() Method

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

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


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

You can also use the optional parameter to filter sibling searches.

The following example returns the following sibling of <h2> that are <p> elements:


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


jQuery next() Method

The next() method returns the next element of the selected element.

The following example returns the following sibling of <h2>:


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


jQuery nextAll() Method

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

The following example returns all of the following <h2> sibling features:


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


jQuery nextUntil() Method

The nextUntil() method returns all of the following relative characteristics between two given arguments.

The following example returns all the brotherly features between <h2> and <h6> element:


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


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

The prev(), prevAll() and prevUntil() modes work as the above but only in reverse: they return the previous sibling elements (skip backwards along with the sibling elements in the DOM tree, instead of moving forward).