如何JSON.stringify一个dom元素? [英] How to JSON.stringify a dom element?

查看:387
本文介绍了如何JSON.stringify一个dom元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为title,如何使用JSON.stringify dom元素,然后将json改回dom元素。

As title , how to JSON.stringify a dom element, and change back the json to a dom element.

任何人都知道该怎么做,谢谢。 / p>

Any one know how to do , thanks.

Here is the code :
var container = document.querySelectorAll('.container')
 var json=JSON.stringify(container)
 {"0":{},"1":{},"2":{},"3":{}}"//result

  expected result:
  {"tagname":"div","class":"container","value":"test","childelement":[...]}


推荐答案

我认为最合理的方法是将DOM元素的哪些属性列入白名单要序列化:

I think the most reasonable approach would be to whitelist which properties of the DOM element you want to serialize:

JSON.stringify(container, ["id", "className", "tagName"])

JSON.stringify 函数的第二个参数允许您可以更改字符串化过程的行为。您可以指定一个带有要序列化的属性列表的数组。有关更多信息,请参见: JSON.stringify

The second parameter of the JSON.stringify function allows you to change the behavior of the stringification process. You can specify an array with the list of properties to serialize. More information here: JSON.stringify

如果您也想序列化其子节点,则需要做一些额外的工作。在这种情况下,您将必须指定替换函数作为 JSON.stringify 的第二个参数,而不是数组。

If you want to serialize its child nodes too, some extra work is needed. In this case you will have to specify a replacer function as the second parameter of JSON.stringify, instead of an array.

let whitelist = ["id", "tagName", "className", "childNodes"];
function domToObj (domEl) {
    var obj = {};
    for (let i=0; i<whitelist.length; i++) {
        if (domEl[whitelist[i]] instanceof NodeList) {
            obj[whitelist[i]] = Array.from(domEl[whitelist[i]]);
        }
        else {
            obj[whitelist[i]] = domEl[whitelist[i]];
        }
    };
    return obj;
}

JSON.stringify(container, function (name, value) {
    if (name === "") {
        return domToObj(value);
    }
    if (Array.isArray(this)) {
        if (typeof value === "object") {
            return domToObj(value);
        }
        return value;
    }
    if (whitelist.find(x => (x === name)))
        return value;
})

replacer函数将 childNodes 中的托管对象转换为本机对象, JSON.stringify 知道如何序列化。 whitelist 数组具有要序列化的属性的列表。您可以在此处添加自己的属性。

The replacer function transforms the hosted objects in childNodes to native objects, that JSON.stringify knows how to serialize. The whitelist array has the list of properties to serialize. You can add your own properties here.

如果您要序列化引用托管对象的其他属性(例如, firstChild )。

Some extra work in the replacer function might be needed if you want to serialize other properties that reference hosted objects (for example, firstChild).

这篇关于如何JSON.stringify一个dom元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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