admin管理员组文章数量:1287810
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);
ofs.o
contains an empty object not the iframe elements WHY??
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);
ofs.o
contains an empty object not the iframe elements WHY??
- See stackoverflow./questions/2303713/… – Crescent Fresh Commented Nov 25, 2010 at 14:16
4 Answers
Reset to default 6JSON (JavaScript Object Notation) is not designed for serializing DOM Nodes, you'll need to pull out the stuff you want by yourself and write it to an object, and then re-create the DOM Nodes from that if you need.
In fact, Chrome doesn't even execute your code:
TypeError: Converting circular structure to JSON
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.
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;
}
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.
本文标签: javascriptJSON serialize a DOM elementStack Overflow
版权声明:本文标题:javascript - JSON serialize a DOM element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741322633a2372293.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论