您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 防城港分类信息网,免费分类信息发布

JS如何遍历DOM文档树

2024/6/8 17:53:48发布7次查看
这次给大家带来js如何遍历dom文档树,js遍历dom文档树的注意事项有哪些,下面就是实战案例,一起来看一下。
本文实例讲述了js遍历dom文档树的方法。分享给大家供大家参考,具体如下:
一 介绍
遍历文档树通过使用parentnode属性、firstchild属性、lastchild属性、previoussibling属性和nextsibling属性来实现。
1、parentnode属性
该属性返回当前节点的父节点。
[pnode=]obj.parentnode
pnode:该参数用来存储父节点,如果不存在父节点将返回“null”。
2、firstchild属性
该属性返回当前节点的第一个子节点。
[cnode=]obj.firstchild
cnode:该参数用来存储第一个子节点,如果不存在将返回“null”。
3、lastchild属性
该属性返回当前节点的最后一个子节点。
[cnode=]obj.lastchild
cnode:该参数用来存储最后一个子节点,如果不存在将返回“null”。
4、previoussibling属性
该属性返回当前节点的前一个兄弟节点。
[snode=]obj.previoussibling
snode:该参数用来存储前一个兄弟节点,如果不存在将返回“null”。
5、nextsibling属性
该属性返回当前节点的后一个兄弟节点。
[snode=]obj.nextsibling
snode:该参数用来存储后一个兄弟节点,如果不存在将返回“null”。
二 应用
遍历文档树,在页面中,通过相应的按钮可以查找到文档的各个节点的名称、类型和节点值。
三 代码
<head> <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,'lastchild');"/><br> <input name="button" type="button" onclick="txt=nodes(txt,'previoussibling');" value="前一个兄弟节点"/> <input type="button" value="最后一个兄弟节点" onclick="txt=nodes(txt,'nextsibling');"/> <input type="button" value="返回根节点" onclick="txt=document.documentelement;txtupdate(txt);"/> </form> <script language="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"previoussibling": if(txt.previoussibling) { txt=txt.previoussibling; } else alert("无兄弟节点"); break; case"nextsibling": if(txt.nextsibling) { txt=txt.nextsibling; } else alert("无兄弟节点"); break; case"parent": if(txt.parentnode) { txt=txt.parentnode; } else alert("无父节点"); break; case"firstchild": if(txt.haschildnodes()) { txt=txt.firstchild; } else alert("无子节点"); break; case"lastchild": if(txt.haschildnodes()) { txt=txt.lastchild; } else alert("无子节点") break; } txtupdate(txt); return txt; } var txt=document.documentelement; txtupdate(txt); --> </script> </body>
四 运行结果
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
react实现手机号的数据同步
babel怎么转换es6的class语法
以上就是js如何遍历dom文档树的详细内容。
防城港分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录