jQuery遍历祖先元素:parentsUntil

时间:2022-12-20 20:40:31

Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.

获得当前匹配元素集合中每个元素的祖先元素,直到(但不包括)被选择器、DOM 节点或 jQuery 对象匹配的元素。

.parentsUntil( [selector] [, filter] )

.parentsUntil( [element] [, filter] )

Given a selector expression that represents a set of DOM elements, the .parentsUntil() method traverses through the ancestors of these elements until it reaches an element matched by the selector passed in the method's argument. The resulting jQuery object contains all of the ancestors up to but not including the one matched by the .parentsUntil() selector.

If the selector is not matched or is not supplied, all ancestors will be selected; in these cases it selects the same elements as the .parents() method does when no selector is provided.

Example:

<ul class="level-1 yes">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2 yes">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
<script>
$(
"li.item-a").parentsUntil(".level-1")
.css(
"background-color", "red");

$(
"li.item-2").parentsUntil( $("ul.level-1"), ".yes" )
.css(
"border", "3px solid green");

</script>

中文文档:http://www.w3school.com.cn/jquery/traversing_parentsuntil.asp

相关的还有:nextUtil jQuery 参考手册 - 遍历