JSON serialize a DOM element

前端 未结 4 1518
孤街浪徒
孤街浪徒 2020-12-18 13:09

If I do:

var el =
{
   o : document.createElement(\"iframe\")
}

var fs = JSON.stringify(el);

and then I try to access with

var ofs = JSON.parse(fs);
         


        
4条回答
  •  清歌不尽
    2020-12-18 14:03

    function elementToObject(element) {
        var el = $(element)[0];
        var o = {tagName: el.tagName};
        _.each(el.attributes, function(attribute){o[attribute.name] = attribute.value;});
        o["children"]=_.map($(el).children(), function(child){return elementToObject(child)});
        return o;
    }
    

    This is working with jquery 3.1.0 and underscore.js.

提交回复
热议问题