Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery traversal - siblings


May 07, 2021 jQuery


Table of contents


jQuery traversal - siblings


Siblings have the same parent element.

With jQuery, you can traverse the element's sibling elements in the DOM tree.


Traverse horizontally in the DOM tree

There are many useful ways for us to traverse horizontally in the DOM tree:

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

Tip: You can refer to the "jQuery traversal method" section of this site for more information about the above methods!


jQuery siblings() method

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

The following example returns all of the sibling elements of slt;h2:

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

Try it out . . .

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

The following example returns all the elements that belong to the compatriot elements of the .

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

Try it out . . .


jQuery next() method

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

The method returns only one element.

The following example returns the next sibling element of slt;h2;

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

Try it out . . .


jQuery nextAll() method

The nextAll() method returns all the sibling elements that follow the selected element.

The following example returns all the sibling elements that followed the .

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

Try it out . . .


jQuery nextUntil() method

The nextUntil() method returns all the sibling elements that follow between two given parameters.

The following example returns all the sibling elements between the elements of slt;h2> and slt;h6?gt;

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

Try it out . . .


jQuery prev(), prevAll() and prevUntil() methods

The prev(), prevAll() and prevUntil() methods work in a similar way to the one above, except in the opposite direction: they return the previous sibling elements (traversing back along the sibling elements in the DOM tree, not forward).