使用javascript获取DOM树 [英] Get DOM tree with javascript

查看:52
本文介绍了使用javascript获取DOM树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午好,我正在开发一个小脚本,分析HTML页面的DOM ,并在屏幕上写出节点树.

Good afternoon, I am developing a small script that analyzes the DOM of an HTML page and write on screen the tree of nodes.

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

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

我已经获得了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>

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

是否有人提出如何绘制嵌套树以浏览您所区分的父节点和子节点?问候和谢谢

推荐答案

您有一个递归DOM reader ,但您还需要一个递归的 outputter .当您需要多级对象(树)时,您还需要处理一维数组.

You have a recursive DOM reader, but you also need a recursive outputter. You're also dealing with a one dimensional array when you need a multi-level object (tree).

我们将从重构 getNodeTree 开始.与其添加到全局数组(代码中的 nodeTree ),不如让它返回一棵树:

We'll start with refactoring getNodeTree. Instead of adding to a global array (nodeTree in your code), let's have it return a tree:

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 相同(对于我们那里的单语朋友,它的意思是显示树"):我们将使其递归工作并返回包含嵌套列表的字符串:

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:

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>

最后:我很抱歉,我的西班牙语JavaScript阅读技能并不尽人意.:)

Finally: My apologies, for my Spanish-JavaScript reading skills are not in their prime. :)

这篇关于使用javascript获取DOM树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆