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"元素之间的所有元素
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"> </script> <style> .container { float:left; margin-left:30px; } .container div { border:1px solid grey; margin:15px auto; } .ancestor1-1,.ancestor2-1,.ancestor3-1,.ancestor4-1 { width:150px; height:150px; } .ancestor1-2,.ancestor2-2,.ancestor3-2,.ancestor4-2 { width:120px; height:120px; } .ancestor1-3,.ancestor2-3,.ancestor3-3,.ancestor4-3 { width:90px; height:90px; } .now1,.now2,.now3,.now4 { width:60px; height:60px; } </style> <script> $(document).ready(function(){ $(".now1").parent().css("border-color","red"); $(".now2").parents().css("border-color","red"); $(".now3").parents(".ancestor3-2").css("border-color","red"); $(".now4").parentsUntil(".ancestor4-1").css("border-color","red"); } ); </script> </head> <body> <div> <div class="container"> <div class="ancestor1-1"><div class="ancestor1-2"><div class="ancestor1-3"><div class="now1">给定元素</div></div></div></div> </div> <div class="container"> <div class="ancestor2-1"><div class="ancestor2-2"><div class="ancestor2-3"><div class="now2">给定元素</div></div></div></div> </div> <div class="container"> <div class="ancestor3-1"><div class="ancestor3-2"><div class="ancestor3-3"><div class="now3">给定元素</div></div></div></div> </div> <div class="container"> <div class="ancestor4-1"><div class="ancestor4-2"><div class="ancestor4-3"><div class="now4">给定元素</div></div></div></div> </div> </div> </body> </html>
效果图:
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17