遍历dom文档的所有节点

遍历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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章