您的当前方法失败,因为未为给定XML文档定义HTML属性。如果提供
text/htmlMIME类型,则该方法应该起作用。
var string = '<!DOCTYPE html><html><head></head><body>content</body></html>';var doc = new DOMParser().parseFromString(string, 'text/html');doc.body.innerHTML; // or doc.querySelector('body').innerHTML// ^ Returns "content"下面的代码
text/html为尚不支持它的浏览器启用MIME类型。
(function(DOMParser) { "use strict"; var DOMParser_proto = DOMParser.prototype , real_parseFromString = DOMParser_proto.parseFromString; // Firefox/Opera/IE throw errors on unsupported types try { // WebKit returns null on unsupported types if ((new DOMParser).parseFromString("", "text/html")) { // text/html parsing is natively supported return; } } catch (ex) {} DOMParser_proto.parseFromString = function(markup, type) { if (/^s*text/htmls*(?:;|$)/i.test(type)) { var doc = document.implementation.createHTMLdocument("") , doc_elt = doc.documentElement , first_elt; doc_elt.innerHTML = markup; first_elt = doc_elt.firstElementChild; if (doc_elt.childElementCount === 1 && first_elt.localName.toLowerCase() === "html") { doc.replaceChild(first_elt, doc_elt); } return doc; } else { return real_parseFromString.apply(this, arguments); } }; }(DOMParser));


