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>
效果图:
以上这篇jQuery向父辈遍历的简单方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持积木网。
JQuery遍历元素的父辈和祖先的方法
JQuery遍历首先我们要知道什么是父亲,儿子,后代,同胞,祖先div元素是ul的父元素,同时是其中所有内容的祖先。ul元素是li元素的父元素,同时是div
利用jquery实现瀑布流3种案例
一、瀑布流是我们常见的案例,这里主要讲述,用jquery的方式实现瀑布流的功能!引言:我们经常见到很多网站的瀑布流功能,如淘宝、京东这些商品
JQuery遍历元素的后代和同胞实现方法
1.遍历后代children()children()方法返回被选元素的所有直接子元素。!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"htm
标签:元素,遍历,方法,瀑布,父辈