Is there a way to JSON.stringify an HTML dom object? [JavaScript]

陌路散爱 提交于 2019-12-06 09:20:48
leaf

Your question is not very clear but I want to give it a try. Inspired from there: https://stackoverflow.com/a/7539198/1636522. Demo: http://jsfiddle.net/wared/fezc6tnt/.

function string2dom (html) {
    var iframe, doc;
    iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    doc = iframe.contentDocument || iframe.contentWindow.document;
    iframe.parentNode.removeChild(iframe);
    doc.open();
    doc.write(html);
    doc.close();
    return doc;
}

var dom = string2dom(''
+ '<html>'
+   '<head>'
+     '<title>test</title>'
+   '</head>'
+   '<body>'
+     '<div id="test">allo la <b>terre</b></div>'
+   '</body>'
+ '</html>'
);

document.body.innerHTML = (
    dom.getElementById('test').innerHTML
);

I was able to figure this out by changing the response type to 'DOMString':

function buildAd(file){
    xhr.open("GET", file);
    xhr.responseType = "DOMString";
    xhr.send();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!