JSON serialize a DOM element

前端 未结 4 1515
孤街浪徒
孤街浪徒 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 13:51

    Building on Alain's prototypejs code, I've updated it using underscore and jQuery, also put into a gist here

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

提交回复
热议问题