2010-11-25 15 views
1

をシリアライズ:JSONはDOM要素

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

var fs = JSON.stringify(el); 

and then I try to access with 

var ofs = JSON.parse(fs); 

ofs.oは空のオブジェクトが含まれていませんiframe要素WHY?

+0

http://stackoverflow.com/questions/2303713/how-to-serialize-dom-node-to-json –

答えて

6

JSON(JavaScriptのオブジェクト表記)はDOMノードを直列化するために設計されたないで、あなたはDOMノードを自分であなたが望むものを引き出し、オブジェクトに書き込み、その後、再作成する必要がありますあなたが必要ならそれから。実際に

、Chromeはも、あなたのコードを実行されません。

TypeError: Converting circular structure to JSON 
+0

を参照してください。エラーの代わりに{}が返されます。 – SuperUberDuper

2

私はこのようにそれをやりました。私は、あなたがJSONに変換することができ、オブジェクトに任意の要素を変換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); 
*/ 

このjavascript関数でコードを置きます。アランのprototypejsコード上

1

ビルは、私は、アンダースコアとjQuery使って更新もこれはjQueryの3.1.0とunderscore.jsで作業している要旨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; 
} 
1
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; 
} 

に入れました。