简体   繁体   English

使用JavaScript获取DOM树

[英]Get DOM tree with javascript

Good afternoon, I am developing a small script that analyzes the DOM of an HTML page and write on screen the tree of nodes . 下午好,我正在开发一个小的脚本, 脚本分析 HTML页面的DOM在屏幕上写出节点树

It is a simple function that is called recursively for get all nodes and their children. 这是一个简单的函数, 递归调用该函数以获取所有节点及其子节点。 The information for each node is stored in an array ( custom object ). 每个节点的信息都存储在一个数组( 自定义对象 )中。

I have gotten get all the nodes in the DOM, but not how to paint in a tree through nested lists. 我已经获得了DOM中的所有节点 ,但是还没有如何通过嵌套列表在树中进行绘制

JSFIDLE JSFIDLE

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

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

Does anyone comes up how to draw a nested tree to glance at the parent and child nodes you distinguish? 是否有人提出如何绘制嵌套树以浏览您所区分的父节点和子节点? Greetings and thank you 问候和谢谢

You have a recursive DOM reader , but you also need a recursive outputter . 您有一个递归的DOM 阅读器 ,但您还需要一个递归的输出程序 You're also dealing with a one dimensional array when you need a multi-level object (tree). 当您需要多级对象(树)时,您还需要处理一维数组。

We'll start with refactoring getNodeTree . 我们将从重构getNodeTree开始。 Instead of adding to a global array ( nodeTree in your code), let's have it return a tree: 与其添加到全局数组(代码中的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;
}

Same for muestraArbol (for our monolingual friends out there, it means "show tree"): We'll have it work recursively and return a string containing nested lists: 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;
}

Finally, if we put it together in a snippet: 最后,如果我们将其汇总在一起:

 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> 

Finally: My apologies, for my Spanish-JavaScript reading skills are not in their prime. 最后:对不起,我的西班牙语JavaScript阅读技能并不完美。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM