Latest web development tutorials

jQuery traversal - Compatriots (siblings)

Compatriots have the same parent element.

By jQuery, you are able to traverse the element's compatriots in the DOM tree.


Level in the DOM tree traversal

There are many useful ways to get us in the DOM tree traversal level:

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

jQuery siblings () method

siblings () method returns the selected element all compatriots elements.

The following example returns the <h2> element all compatriots:

Examples

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

try it"

You can also use the optional parameters to filter the search for compatriots element.

The following example returns belong to <h2> element all compatriots <p> element:

Examples

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

try it"


jQuery next () method

next () method returns the selected element to the next element compatriots.

This method returns only one element.

The following example returns the <h2> element next compatriots:

Examples

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

try it"


jQuery nextAll () method

nextAll () method returns all elements follow fellow of the selected element.

The following example returns the <h2> element all compatriots to follow:

Examples

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

try it"


jQuery nextUntil () method

nextUntil () method returns between all elements of the two compatriots to follow the given parameters.

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

Examples

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

try it"


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

Work prev (), prevAll () and prevUntil () method is similar to the above method, but only in the opposite direction: they return in front of compatriot elements (in the DOM tree traversal backward along compatriots element instead forward).