美文网首页前端让前端飞前端开发那些事儿
算法二:DOM - 将DOM节点元素转换成JSON字符串

算法二:DOM - 将DOM节点元素转换成JSON字符串

作者: 张中华 | 来源:发表于2021-02-08 07:53 被阅读0次

    题目:
    将DOM节点元素转换成JSON的格式
    例如

    <div class="root">
         <div class="child1"><p></p></div>
        <span></span>
         <div><div><p></p></div></div>
        <p></p>
    </div>
    

    转换显示成(简写,大致表达个意思):
    {"tagName":"DIV", className="root", childs:[{"tagName":"DIV", className="root",childs:[]}]}

    乍一看上去并不是很难,递归,找出各个节点的child节点即可,可真正当场写出代码还是需要锻炼锻炼,反正我当时没写出来,课后补习:
    试一试:http://jsrun.net/VPaKp/edit
    HTML File:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=, initial-scale=">
        <meta http-equiv="X-UA-Compatible" content="">
        <title></title>
    </head>
    <body>
        <div class="root">
            <div class="child1"><p></p></div>
            <span class="span1"><span></span></span>
            <div><div><p class="p1"></p></div></div>
            <p><span></span></p>
        </div>
    </body>
    </html>
    

    JS File:

    function convertToJson() {
        const root = document.getElementsByClassName('root')[0];
        const output = new Object();
        output.tagName = root.tagName;
        output.className = root.className;
        output.childs = getChilds(root);
    
        console.log(JSON.stringify(output));
    }
    
    function getChilds(node) {
        const childs = node.children;
        const result = new Array();
        if(!childs || childs.length === 0) return result;
        for (const child of childs) {
            const childOutput = new Object();
            childOutput.tagName = child.tagName;
            childOutput.className = child.className;
            childOutput.childs = getChilds(child);
            result.push(childOutput);
        }
        return result;
    }
    convertToJson();
    

    运行结果:
    {"tagName":"DIV","className":"root","childs":[{"tagName":"DIV","className":"child1","childs":[{"tagName":"P","className":"","childs":[]}]},{"tagName":"SPAN","className":"span1","childs":[{"tagName":"SPAN","className":"","childs":[]}]},{"tagName":"DIV","className":"","childs":[{"tagName":"DIV","className":"","childs":[{"tagName":"P","className":"p1","childs":[]}]}]},{"tagName":"P","className":"","childs":[{"tagName":"SPAN","className":"","childs":[]}]}]}

    随便找了一个格式化的网站把json字符串格式化显示下:



    在对比下HTML文件目录:

        <div class="root">
            <div class="child1"><p></p></div>
            <span class="span1"><span></span></span>
            <div><div><p class="p1"></p></div></div>
            <p><span></span></p>
        </div>
    

    就是这么回事。目前就是想到这个方法了,至于是不是最优就不得而知啦~

    相关文章

      网友评论

        本文标题:算法二:DOM - 将DOM节点元素转换成JSON字符串

        本文链接:https://www.haomeiwen.com/subject/lmaztltx.html