[英]Get DOM tree with javascript
下午好,我正在开发一个小的脚本, 该脚本分析 HTML页面的DOM并在屏幕上写出节点树 。
这是一个简单的函数, 递归调用该函数以获取所有节点及其子节点。 每个节点的信息都存储在一个数组( 自定义对象 )中。
我已经获得了DOM中的所有节点 ,但是还没有如何通过嵌套列表在树中进行绘制 。
https://jsfiddle.net/06krpdyh/
<html>
<head>
<title>Formulario para validar</title>
<script type="text/javascript" src="actividad_1.js">Texto script</script>
</head>
<body>
<p>Primer texto que se visualiza en la Pagina</p>
<div>Esto es un div</div>
<div>Otro div que me encuentro</div>
<p>Hay muchos parrafos</p>
<ul>
<li>Lista 1</li>
<li>Lista 2</li>
<li>Lista 3</li>
</ul>
<button type="button" id="muestra_abol">Muestra Arbol DOM</button>
</body>
</html>
// Ejecuta el script una vez se ha cargado toda la página, para evitar que el BODY sea NULL.
window.onload = function(){
// Evento de teclado al hacer click sobre el boton que muestra el arbol.
document.getElementById("muestra_abol").addEventListener("click", function(){
muestraArbol();
});
// Declara el array que contendrá los objetos con la información de los nodos.
var nodeTree = [];
// Recoge el nodo raíz del DOM.
var obj_html = document.documentElement;
// Llama a la función que genera el árbol de nodos de la página.
getNodeTree(obj_html);
console.log(nodeTree);
// Función que recorre la página descubriendo todo el árbol de nodos.
function getNodeTree(node)
{
// Comprueba si el nodo tiene hijos.
if (node.hasChildNodes())
{
// Recupera la información del nodo.
var treeSize = nodeInfo(node);
// Calcula el índice del nodo actual.
var treeIndex = treeSize - 1;
// Recorre los hijos del nodo.
for (var j = 0; j < node.childNodes.length; j++)
{
// Comprueba, de forma recursiva, los hijos del nodo.
getNodeTree(node.childNodes[j]);
}
}
else
{
return false;
}
}
// Función que devuelve la información de un nodo.
function nodeInfo(node,)
{
// Declara la variable que contendrá la información.
var data = {
node: node.nodeName,
parent: node.parentNode.nodeName,
childs: [],
content: (typeof node.text === 'undefined'? "" : node.text)
}
var i = nodeTree.push(data);
return i;
}
// Función que devuelve los datos de los elementos hijos de un nodo.
function muestraArbol()
{
var txt = "";
// Comprueba si existen nodos.
if (nodeTree.length > 0)
{
// Recorre los nodos.
for (var i = 0; i < nodeTree.length; i++)
{
txt += "<ul><li>Nodo: " + nodeTree[i].node + "</li>";
txt += "<li> Padre: " + nodeTree[i].parent + "</li>";
txt += "<li>Contenido: " + nodeTree[i].content + "</li>";
txt += "</ul>";
}
document.write(txt);
}
else
{
document.write("<h1>No existen nodos en el DOM.</h1>");
}
}
};
是否有人提出如何绘制嵌套树以浏览您所区分的父节点和子节点? 问候和谢谢
您有一个递归的DOM 阅读器 ,但您还需要一个递归的输出程序 。 当您需要多级对象(树)时,您还需要处理一维数组。
我们将从重构getNodeTree
开始。 与其添加到全局数组(代码中的nodeTree
), nodeTree
让它返回一棵树:
function getNodeTree (node) {
if (node.hasChildNodes()) {
var children = [];
for (var j = 0; j < node.childNodes.length; j++) {
children.push(getNodeTree(node.childNodes[j]));
}
return {
nodeName: node.nodeName,
parentName: node.parentNode.nodeName,
children: children,
content: node.innerText || "",
};
}
return false;
}
对muestraArbol
来说muestraArbol
(对于在那里的单语朋友来说,它的意思是“显示树”):我们将使其递归地工作,并返回包含嵌套列表的字符串:
function muestraArbol (node) {
if (!node) return "";
var txt = "";
if (node.children.length > 0) {
txt += "<ul><li>Nodo: " + node.nodeName + "</li>";
txt += "<li> Padre: " + node.parentName + "</li>";
txt += "<li>Contenido: " + node.content + "</li>";
for (var i = 0; i < node.children.length; i++)
if (node.children[i])
txt += "<li> Hijos: " + muestraArbol(node.children[i]) + "</li>";
txt += "</ul>";
}
return txt;
}
最后,如果我们将其汇总在一起:
var nodeTree = getNodeTree(document.documentElement); console.log(nodeTree); function getNodeTree(node) { if (node.hasChildNodes()) { var children = []; for (var j = 0; j < node.childNodes.length; j++) { children.push(getNodeTree(node.childNodes[j])); } return { nodeName: node.nodeName, parentName: node.parentNode.nodeName, children: children, content: node.innerText || "", }; } return false; } function muestraArbol(node) { if (!node) return ""; var txt = ""; if (node.children.length > 0) { txt += "<ul><li>Nodo: " + node.nodeName + "</li>"; txt += "<li> Padre: " + node.parentName + "</li>"; txt += "<li>Contenido: " + node.content + "</li>"; for (var i = 0; i < node.children.length; i++) if (node.children[i]) txt += "<li> Hijos: " + muestraArbol(node.children[i]) + "</li>"; txt += "</ul>"; } return txt; } document.getElementById("muestra_abol").addEventListener("click", function() { document.getElementById("result").innerHTML = muestraArbol(nodeTree); });
<title>Formulario para validar</title> <body> <p>Primer texto que se visualiza en la Pagina</p> <div>Esto es un div</div> <div>Otro div que me encuentro</div> <p>Hay muchos parrafos</p> <ul> <li>Lista 1</li> <li>Lista 2</li> <li>Lista 3</li> </ul> <button type="button" id="muestra_abol">Muestra Arbol DOM</button> <div id="result"></div> </body>
最后:对不起,我的西班牙语JavaScript阅读技能并不完美。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.