代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>New Page</title>
</head>
<script type="text/javascript">
<!--
function allNodeText(e){
var e = (typeof e == "string") ? document.getElementById(e) : e;
var arrText = [];
getStrings(e, arrText);
return arrText.join("");
if(e.nodeType == 3){
arrText.push(e.data);
}else if(e.nodeType == 1){
for(var m = e.firstChild; m != null; m = m.nextSibling){
getStrings(m, arrText);// 循环体
}
}
}
/***********************************************************
* 主要讲解下getStrings这个递归方法获取所有节点的流程
*首先,传入的节点为Node1,nodeType==1走入 for分支 m = e.firstChild节点为nodeText1,
*进入getStrings递归由于 nodeType==3则添加数组中结束,由于循环体结束,则便运行条件
*m = m.nextSibling.nodeText1, 的兄弟节点便是Node2的span,span又走nodeType==1分支
*取得firstChild为 NodeText2然后进入递归到nodeType==3便再次结束递归走m=m.nextSibling
*一直到所有的节点都走完,然后走入第二个节点同上步骤.
***********************************************************/
}
//-->
</script>
<body onload="alert(allNodeText('Node1'))">
<span id="Node1">
NodeText1,
<span id="Node2">
NodeText2,
<b>
NodeText3,
</b>
<i>
NodeText4,
</i>
</span>
<span id="Node3">
NodeText5
</span>
</span>
</body>
</html>
<head><title>New Page</title>
</head>
<script type="text/javascript">
<!--
function allNodeText(e){
var e = (typeof e == "string") ? document.getElementById(e) : e;
var arrText = [];
getStrings(e, arrText);
return arrText.join("");
function getStrings(e, arrText){
if(e.nodeType == 3){
arrText.push(e.data);
}else if(e.nodeType == 1){
for(var m = e.firstChild; m != null; m = m.nextSibling){
getStrings(m, arrText);// 循环体
}
}
}
/***********************************************************
* 主要讲解下getStrings这个递归方法获取所有节点的流程
*首先,传入的节点为Node1,nodeType==1走入 for分支 m = e.firstChild节点为nodeText1,
*进入getStrings递归由于 nodeType==3则添加数组中结束,由于循环体结束,则便运行条件
*m = m.nextSibling.nodeText1, 的兄弟节点便是Node2的span,span又走nodeType==1分支
*取得firstChild为 NodeText2然后进入递归到nodeType==3便再次结束递归走m=m.nextSibling
*一直到所有的节点都走完,然后走入第二个节点同上步骤.
***********************************************************/
}
//-->
</script>
<body onload="alert(allNodeText('Node1'))">
<span id="Node1">
NodeText1,
<span id="Node2">
NodeText2,
<b>
NodeText3,
</b>
<i>
NodeText4,
</i>
</span>
<span id="Node3">
NodeText5
</span>
</span>
</body>
</html>