<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
function demo()
{
var divObj = document.getElementById("divid1"); //根据ID获取
divObj.style.backgroundColor = "red";
var parentNode = divObj.parentNode; //父节点
//getNodeInfo(parentNode);
var childNodes = divObj.childNodes; //子节点
//getNodeInfo(childNodes[0]);
var preNode = divObj.previousSibling.previousSibling; //前一个节点
//getNodeInfo(preNode);
var nextNode = divObj.nextSibling; //下一个节点
//getNodeInfo(nextNode);
//获取节点的方法:
//1、getElementById(HTML标签中定义的id值)
//2、getElementsByName(HTML标签中定义的name值)
//3、getElementsByTagName(HTML标签名)
var tabNode = document.getElementById("table1");
var tdNodes = tabNode.getElementsByTagName("td");
getNodeInfo(tdNodes[0].childNodes[0]);
}
function getNodeInfo(node)
{
alert("name:"+node.nodeName+"...type:"+node.nodeType+"...value:"+node.nodeValue+"---");
}
//--------------------------打印层级节点
var str = "";
function listNode(node, level)
{
printInfo(node, level);
level++;
var nodes = node.childNodes;
alert(nodes);
for(var x=0; x<nodes.length; x++)
{
if(nodes[x].hasChildNodes())
listNode(nodes[x], level);
else
printInfo(node, level);
}
}
function printInfo(node, level)
{
str += getSpace(level) + "name:"+node.nodeName+"...type:"+node.nodeType+"...value:"+node.nodeValue+"<br/>";
}
function getSpace(level)
{
var s = "";
for(var x=0; x<level; x++)
{
s += "|----";
}
return s;
}
function showNode()
{
listNode(document, 0);
document.write(str);
}
</script>
</head>
<body>
<input type="button" value="点击" onclick="showNode()" />
<div id="divid1">
ssssssssss
</div>
<table id="table1" border="1px">
<tr>
<td>单元格一</td>
<td>单元格二</td>
</tr>
<tr>
<td>单元格三</td>
<td>单元格四</td>
</tr>
</table>
</body>
</html>