<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>遍历文档树</title>
</head>
<body>
<h3 id="h1">三号标题</h3>
<b>加粗内容</b>
<form name="frm" action="#" method="get">
节点名称:<input type="text" id="na" /><br />
节点类型: <input type="text" id="ty" /><br />
节点的值: <input type="text" id="va" /><br />
<input type="button" value="父节点" onclick="txt=nodeS(txt,'parent');"/>
<input type="button" value="第一个子节点" onclick="txt=nodeS(txt,'firstChild');" />
<input type="button" value="后一个兄弟节点" onclick="txt=nodeS(txt,'nextSibling');" />
</form>
</body>
<script type="text/javascript">
function txtUpdate(txt){
window.document.frm.na.value = txt.nodeName;
window.document.frm.ty.value = txt.nodeType;
window.document.frm.va.value = txt.nodeValue;
}
function nodeS(txt,nodeName){
switch (nodeName){
case "parent":
if (txt.parentNode) {
txt = txt.parentNode;
} else{
alert("无父节点");
}
break;
case "firstChild":
if (txt.hasChildNodes()) {
txt = txt.firstChild;
} else{
alert("无子节点");
}
break;
case "nextSibling":
if(txt.nextSibling){
txt = txt.nextSibling;
}else{
alert("无兄弟节点");
}
break;
default:
break;
}
txtUpdate(txt);
return txt;
}
var txt = document.documentElement;
txtUpdate(txt);
</script>
</html>
js 遍历文档树
最新推荐文章于 2023-11-29 15:25:08 发布
本文介绍了一个简单的HTML页面,该页面包含一个用于演示如何通过JavaScript遍历文档对象模型(DOM)树的表单。用户可以通过点击按钮来获取当前节点及其父节点、第一个子节点和后一个兄弟节点的信息。
711

被折叠的 条评论
为什么被折叠?



