时间:2021-11-14 10:25:05 | 栏目: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>
效果图: