jQuery Siblings

jQuery Traversing - Siblings

Siblings are elements that share the exact same parent in the HTML DOM tree.

With jQuery, you can seamlessly traverse sideways to target elements next to each other.

This is particularly helpful for form validations and interactive UI menus.


Methods for Traversing Sideways

jQuery boasts a wide array of methods for targeting sibling elements:


The siblings() Method

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

If you have three paragraphs in a div, selecting one and calling siblings() will return the other two.

The siblings() Example:

$(document).ready(function(){
  // Styles all siblings of the h2 element
  $("h2").siblings().css({"color": "red", "border": "2px solid red"});
});

You can also filter siblings. $("h2").siblings("p") returns only sibling elements that are paragraphs.


The next() Method

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

It only looks at the exact element appearing immediately after it in the HTML code.

The next() Example:

$(document).ready(function(){
  // Styles only the h3 that comes right after the h2
  $("h2").next().css({"color": "blue", "border": "2px solid blue"});
});

Similarly, the prev() method returns the previous sibling element that comes immediately before it.


The nextAll() and prevAll() Methods

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

It targets everything that comes after the element in the DOM tree.

The nextAll() Example:

$(document).ready(function(){
  // Styles everything after the h2
  $("h2").nextAll().css({"color": "green", "border": "2px solid green"});
});

The prevAll() method does the same, but it grabs everything coming before the selected element.


The nextUntil() Method

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

This creates a perfect slice of elements in a list.

The nextUntil() Example:

$(document).ready(function(){
  // Returns elements between the h2 and the h6
  $("h2").nextUntil("h6").css({"color": "purple", "border": "2px solid purple"});
});

Exercise 1 of 2

?

Which method selects all the siblings that appear AFTER the selected element?