jQuery Traversal - prevUntil() Method

Example

Find all同胞 elements of each p element with the class name "selected":

$("p").siblings(".selected")

Try it yourself

Definition and Usage

The siblings() method gets同胞 of each element in the matching set, and filtering by selector is optional.

Syntax

.siblings(selector)
Parameter Description
selector String value, containing the selector expression used to match elements.

Detailed Description

If a jQuery object representing a set of DOM elements is given, the .siblings() method allows us to search for同胞 elements of these elements in the DOM tree and construct a new jQuery object with matching elements.

This method accepts an optional selector expression, of the same type as the parameter passed to the $() function. If this selector is applied, elements will be filtered by checking whether they match the selector.

Think about this page with a basic nested list:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

If we start from the third item, we can find the同胞 elements of this element:

$('li.third-item');.siblings();.css('background-color', 'red');

Try it yourself

The result of the call here is to set the background color of items 1, 2, 4, and 5 to red. Set to red background. Since we have not applied a selector expression, all同胞 elements naturally become part of the object. If a selector has been applied, only the matching items in the four lists will be included.

The original element is not included in the同胞 elements, it is very important to remember this when we intend to find all elements at a specific level of the DOM tree.