Javascript 递归打印Document层次关系的例子

发布时间:2019-12-10编辑:脚本学堂
本文介绍了Javascript 递归打印Document层次关系的方法,有关js递归打印dom数据的例子,有需要的朋友参考下。

例子,javascript 递归打印Document层次关系。
 

复制代码 代码示例:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>递归显示节点层次关系_www.jb200.com</title>
    <script type="text/javascript">
        var ResultStr = "";
        function ListNode(node,level) {
            PrintInfo(node, level);
            level++;
            var nodes = node.childNodes;
            for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].hasChildNodes()) {
                    ListNode(nodes[i], level);  //递归
                }
                else {
                    PrintInfo(nodes[i], level);
                }
            }
        }

        function getSpace(level) {
            var s = "";
            for (var i = 0; i < level; i++) {
                s+="!----"
            }
            return s;
        }

        function PrintInfo(node, level) {
            ResultStr += getSpace(level) + "Name:" + node.nodeName +
                                "...Type:" + node.nodeType + "...Value:" + node.nodeValue + "<br />";
        }

        function getDocAllInfo() {
            ResultStr = "";
            ListNode(document, 0);
            document.write(ResultStr);
        }
    </script>
</head>
<body>
    <input type="button" value="测试" onclick="getDocAllInfo()" />
    <div id="divDemo">div内容</div>
    <table>
        <tr>
            <td>单元格1</td>
            <td>单元格2</td>
        </tr>
        <tr>
            <td>单元格3</td>
            <td>单元格4</td>
        </tr>
    </table>
    <input type="text" />
    <span>我是SPAN</span>
    <!--注释-->
</body>
</html>