JQUERY .closest() .parents()区别

本文通过一个具体的示例对比了 jQuery 中 .closest() 和 .parents() 方法的区别。.closest() 方法从当前元素开始向上查找,直到找到匹配的选择器元素为止。而 .parents() 方法则从当前元素的父级开始,一直遍历到文档的根元素,并返回所有匹配的选择器元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
<style>
.ancestors *
{ 
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>

</head>
<body>
<ul id="one" class="level-1">
  <li class="item-i">I</li>
  <li id="ii" class="item-ii">II
  <ul class="level-2">
    <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-1').parents('ul').css('background-color', 'red');
</script>
</body>

<!-- In this example, $("span").closest("ul") means that we search for the first ancestor of span that is an ul element. The CLOSEST ancestor of span is li, but since we are looking for a div, jQuery skips the li element and continue the search for the next ancestor, on and on until it locates our search for ul. If we use the parents() method instead, it will return both ul ancestors. --> 
</html>			

.closest() .parents()
从当前元素开始 从父元素开始
沿 DOM 树向上遍历,直到找到已应用选择器的一个匹配为止。 沿 DOM 树向上遍历,直到文档的根元素为止,将每个祖先元素添加到一个临时的集合;如果应用了选择器,则会基于该选择器对这个集合进行筛选。 
返回包含零个或一个元素的 jQuery 对象 返回包含零个、一个或多个元素的 jQuery 对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值