jQuery向父辈遍历的方法

通过DOM树可以可容易的访问到html文档中的所有元素

  例如向上访问父辈的元素有以下方法

    1.parent()方法可以得到所定元素的直接父元素

      $("span").parent();得到<span>元素的直接父元素

    2.parents()方法得到给定元素的所有父元素

      $("span").parents();得到<span>元素的所有父元素

      $("span").panents(".text");得到<span>元素的父元素中class="text"的元素

    3.parentsUntil()方法得到两个给定元素之间的元素

      $("span").parentsUntil(".text");得到<span>元素与class="text"元素之间的所有元素

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4  <meta charset="UTF-8">
 5  <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
 6 </script>
 7  <style>
 8  .container
 9  {
10     float:left;
11     margin-left:30px;
12  }
13 .container div
14   {
15     border:1px solid grey;
16     margin:15px auto;
17   }
18 .ancestor1-1,.ancestor2-1,.ancestor3-1,.ancestor4-1
19 {
20     width:150px;
21     height:150px;
22 }  
23 .ancestor1-2,.ancestor2-2,.ancestor3-2,.ancestor4-2
24 {
25     width:120px;
26     height:120px;
27 }
28 .ancestor1-3,.ancestor2-3,.ancestor3-3,.ancestor4-3
29 {
30     width:90px;
31     height:90px;
32 }
33 .now1,.now2,.now3,.now4
34 {
35     width:60px;
36     height:60px;
37 }
38  </style>
39  <script>
40 $(document).ready(function(){
41 $(".now1").parent().css("border-color","red");
42 $(".now2").parents().css("border-color","red");
43 $(".now3").parents(".ancestor3-2").css("border-color","red");
44 $(".now4").parentsUntil(".ancestor4-1").css("border-color","red");
45 }
46 );
47  </script>
48 </head>
49 <body>
50 <div>
51     <div class="container">
52         <div class="ancestor1-1"><div class="ancestor1-2"><div class="ancestor1-3"><div class="now1">给定元素</div></div></div></div>
53     </div>
54     <div class="container">
55         <div class="ancestor2-1"><div class="ancestor2-2"><div class="ancestor2-3"><div class="now2">给定元素</div></div></div></div>
56     </div>
57     <div class="container">
58         <div class="ancestor3-1"><div class="ancestor3-2"><div class="ancestor3-3"><div class="now3">给定元素</div></div></div></div>
59     </div>
60     <div class="container">
61         <div class="ancestor4-1"><div class="ancestor4-2"><div class="ancestor4-3"><div class="now4">给定元素</div></div></div></div>
62     </div>
63 </div>
64 </body>
65 </html>

 

效果图:

 

转载于:https://www.cnblogs.com/it-body/p/5878313.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值