后代遍历
后代遍历又称向下遍历,常用的方法有children()、find()和contents()方法,通过向下遍历DOM树的方式来查找元素的后台元素。
1. children()方法:
children()方法用于返回所匹配元素的直接子元素,并允许使用选择器进行筛选,其语法格式如下:
$(selector).children([childSelector])
- $(selector):表示所匹配的元素
- childSelector(可选):表示指定的选择器
- 当方法提供childSelector参数时,表示返回所匹配元素的子元素,并使用childSelector选择器进行筛选,否则返回所有匹配元素的直接子元素
2. find()方法:
find()方法用于返回所匹配元素的后代元素,并允许使用指定的选择器进行筛选,其语法格式如下:
$(selector).find(expression | jQueryObject | element)
- $(selector):表示所匹配的元素
- 该方法的参数是一个表达式、jQuery对象或DOM对象,表示使用其中一种方式对元素的所有后代元素进行筛选
3. contents()方法:
contents()方法用于返回所匹配元素的子元素(包括文本节点和注释节点),还可以用于查找iframe页面中的子元素,其语法格式如下:
$(selector).contents()
示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>后代元素-jQuery遍历</title>
<script type="text/javascript" src="js/jquery-1.x.js">
</script>
<style type="text/css">
.imageDiv img{ width:100px;}
</style>
</head>
<body>
<div class="containerDiv">
<p>
<span>T恤大全</span>
</p>
<hr/>
<div class="imageDiv">
<span><img src="images/shirt.jpg" /></span>
</div>
<div>
<span>顾客的需求是我们创意的源泉。</span>
</div>
<span></span>
<iframe src="childrenNode_iframe.html" ></iframe>
</div>
<script type="text/javascript">
$(function (e) {
//showChildrenNode();
//showFindNode();
showContentsNode();
});
function showChildrenNode(){
//返回匹配元素的所有的直接子元素
//var childrenNode=$(".containerDiv").children();
//var childrenNode=$(".containerDiv").children(".imageDiv");
var childrenNode=$(".containerDiv").children("span");
//返回匹配元素中的直接div子元素
for(var c=0;c<childrenNode.length;c++){
console.log("--------------------------------------");
console.log(childrenNode[c].outerHTML);
}
}
function showFindNode(){
//查找匹配元素中的直接或间接span子元素(所有的后代元素)
var findNode=$(".containerDiv").find("span");
for(var f=0;f<findNode.length;f++){
console.log("--------------------------------------");
console.log(findNode[f].outerHTML);
}
}
function showContentsNode(){
//查找匹配元素的所有后代元素(包括文本元素和注释元素)
var contentsNode=$(".containerDiv").contents();
for(var c=0;c<contentsNode.length;c++){
console.log("--------------------------------------");
switch(contentsNode[c].nodeType){
case 1://元素节点
console.log(contentsNode[c].outerHTML);
break;
case 3://文本节点
console.log($(contentsNode[c]).context);
break;
case 8://注释节点
console.log($(contentsNode[c]).context);
break;
}
}
//获取iframe子页面中的所有的div元素
console.log("在iframe页面中查找的节点:"+$(".containerDiv iframe").contents().find("div").html());
}
</script>
</body>
</html>