获取使用JavaScript的DOM树

3

我正在开发一个小脚本,用于分析 HTML 页面的 DOM,并在屏幕上显示节点树。

这是一个简单的函数,通过递归方式调用以获取所有节点及其子节点。每个节点的信息存储在一个数组中(自定义对象)。

我已经获取到了 DOM 中的所有节点,但不知道如何使用嵌套列表进行树形绘制。

###JSFIDLE### https://jsfiddle.net/06krpdyh/

###HTML####

<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>

###JS###

// 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>");
        }
    }   
};

有人想到了如何绘制一个嵌套树来一目了然地区分父节点和子节点吗?
1个回答

7
您有一个递归的DOM阅读器,但您还需要一个递归的输出器。同时,您正在处理一维数组,但您需要一个多级对象(树形结构)。
我们可以从重构 `getNodeTree` 函数开始。不要再像你的代码中那样向全局数组(`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(对于我们的单语朋友,它的意思是“显示树”):我们将使其递归工作并返回包含嵌套列表的字符串:
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阅读能力不是最好的。 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接