主要分为三种,祖先遍历,后代遍历,以及相关过滤。
祖先遍历:
demo:
<script>
$(document).ready(function(){
$("span").parentsUntil("div").css({"color":"red","border":"2px solid red"});
});
</script>
</head>
<body class="ancestors"> body (曾曾祖父元素)
<div style="width:500px;">div (曾祖父元素)
<ul>ul (祖父元素)
<li>li (父元素)
<span>span</span>
</li>
</ul>
</div>
</body>
后代遍历:
demo:
<script>
$(document).ready(function(){
$("h2").siblings("p").css({"color":"red","border":"2px solid red"});
});
</script>
</head>
<body class="siblings">
<div>div (父元素)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div>
过滤:
demo:
<script>
$(document).ready(function(){
$("p").filter(".url").css("background-color","yellow");
});
</script>
</head>
<body>
<h1>欢迎访问我的主页</h1>
<p>菜鸟教程 (index 0).</p>
<p class="url">http://www.runoob.com (index 1)。</p>
<p>google (index 2).</p>
<p class="url">http://www.google.com (index 3)。</p>
</body>