【问题标题】:Get DOM tree with javascript使用 javascript 获取 DOM 树
【发布时间】:2016-01-27 16:28:28
【问题描述】:

下午好,我正在开发一个小脚本,用于分析 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>");
        }
    }   
};

有没有人想出如何画一个嵌套树来看看你区分的父节点和子节点? 问候并感谢您

【问题讨论】:

    标签: javascript dom tree


    【解决方案1】:

    你有一个递归 DOMreader,但你还需要一个递归 outputter。当您需要多级对象(树)时,您还需要处理一维数组。

    我们将从重构 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;
    }
    

    最后,如果我们把它放在一个 sn-p 中:

    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 阅读能力还没有达到巅峰。 :)

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 2016-04-09
      • 2023-03-18
      • 2014-07-22
      • 1970-01-01
      相关资源
      最近更新 更多