您好,欢迎访问一九零五行业门户网

如何获取DOM文档树内所有数据

这次给大家带来如何获取dom文档树内所有数据,获取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>
四 运行结果
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js插入dom对象节点方法总结
怎样操作babel转换es6
以上就是如何获取dom文档树内所有数据的详细内容。
其它类似信息

推荐信息