jQuery 遍歷 - 后代
向下遍歷 DOM
children()
find()
children() 方法
children() 方法返回被選元素的所有直接子元素(僅兒子輩)。
參數(shù)可選,添加參數(shù)表示通過選擇器進(jìn)行過濾,對元素進(jìn)行篩選。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .descendants * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("div").children("p.1").css({"color":"blue","border":"5px solid green"}); }); </script> </head> <body> <div class="descendants" style="width:300px;"> <p class="1">p (兒子元素) <span>span (孫子元素)</span> </p> <p class="2">p (兒子元素) <span>span (孫子元素)</span> </p> </div> </body> </html>
返回類名為 "1" 的所有 <p> 元素,并且它們是 <div> 的直接子元素
find() 方法
find() 方法返回被選元素的后代元素,一路向下直到最后一個后代。
參數(shù)是必選的,可以為選擇器、jQuery對象可元素來對元素進(jìn)行篩選。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .descendants * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("div").find("span").css({"color":"red","border":"3px solid blue"}); }); </script> </head> <body> <div class="descendants" style="width:300px;"> <p>p (兒子元素) <span>span (孫子元素)</span> </p> <p>p (兒子元素) <span>span (孫子元素)</span> </p> </div> </body> </html>
返回屬于 <div> 后代的所有 <span> 元素。