jQuery Traversal - prevUntil() Method
Example
Find all sibling elements of each p element with the class name "selected":
$("p").siblings(".selected")
Definition and Usage
The siblings() method gets the siblings 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 sibling 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 parameters 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 sibling elements of this element:
$('li.third-item').siblings().css('background-color', 'red');
The result of the call here is to set the background color of items 1, 2, 4, and 5 to red. Set the background color to red. Since we have not applied a selector expression, all sibling elements naturally become part of the object. If a selector has been applied, it will only include the matching items from the four lists.
The original element is not included in the sibling elements, it is very important to remember this when we intend to find all elements at a specific level of the DOM tree.