JSON serialize a DOM element

前端 未结 4 1514
孤街浪徒
孤街浪徒 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:52

    I did it like this. I put the code on github

    function elementToObject(element, o) {
        var el = $(element);
        var o = {
           tagName: el.tagName
        };
        var i = 0;
        for (i ; i < el.attributes.length; i++) {
            o[el.attributes[i].name] = el.attributes[i].value;
        }
    
        var children = el.childElements();
        if (children.length) {
          o.children = [];
          i = 0;
          for (i ; i < children.length; i++) {
            child = $(children[i]);
            o.children[i] = elementToObject(child, o.children) ;
          }
        }
        return o;
      }
    /*
      exemple:
      a = elementToObject(document.body);
      Object.toJSON(a);
    */
    

    This javascript function convert any element to an object, then you can convert it to json.

提交回复
热议问题