遍历dom文档的所有节点
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>node.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=GBK">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<div align="center">
<div id="head">
用户名:<input type="text" name="uname" id="uname"/>
</div>
</div>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
var rootNode = document.documentElement;
itor(rootNode);
//打印输出
document.write(msg);
}
function itor(node){
//首先判断是否是元素节点
if (node.nodeType == 1) {
//是元素节点,打印
display(node);
for (var i = 0; i < node.length; i++) {
var attr = node.attributes[i];
//判断属性节点是否存在
if (attr.specified) {
display(attr);
}
}
//判断是否有孩子节点
if (node.hasChildNodes()) {
var sonNodes = node.childNodes;
for (var j = 0; j < sonNodes.length; j++) {
var sonNode = sonNodes[j];
//用到递归方法
itor(sonNode);
}
}
}else {
display(node);
}
}
var msg = "";
function display(node){
msg += "<br/>节点的名称" + node.nodeName + "节点的值:" + node.nodeValue + "节点的类型:" + node.nodeType;
}
</script>