jQuery Traversal - parentsUntil() Method
Example
Find the ancestor elements of <li class="item-a"> until <ul class="level-1">, and set their background to red. Also, find all ancestor elements of <li class="item-2"> with the class name "yes" until <ul class="level-1">, and set their border to blue:
$("li.item-a");.parentsUntil(".level-1"); .css("background-color", "red"); $("li.item-2");.parentsUntil($("ul.level-1"), ".yes"); .css("border", "3px solid blue");
Definition and Usage
The parentsUntil() method gets the ancestor elements of each element in the current matched element set until (but not including) the element that matches the selector, DOM node, or jQuery object.
Syntax 1
.parentsUntil(selector,filter)
Parameters | Description |
---|---|
selector | Optional. A string value specifying where to stop matching ancestor elements. |
filter | Optional. A string value containing the selector expression used to match elements. |
Syntax 2
.parentsUntil(element,filter)
Parameters | Description |
---|---|
element | Optional. A DOM node or jQuery object indicating where to stop matching ancestor elements. |
filter | Optional. A 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 .parentsUntil() method allows us to search for the ancestor elements of these elements in the DOM tree until we encounter an element that matches the selector (passed as a parameter to the method). The returned jQuery object contains all ancestor elements but does not include the element that matches the selector specified by the .parentsUntil() method.
If no match is found or a selector is not applied, all ancestor elements of the selection will be selected; in this case, the elements selected by the method are the same as those selected by .parents() without a selector provided.
For jQuery 1.6, a DOM node or jQuery object, rather than a selector, can be used as the first parameter of the .parentsUntil() method.
This method accepts an optional selector expression as its second parameter. If this parameter is applied, elements will be filtered by checking if they match the selector.