JavaScript DOMParser访问innerHTML和其他属性

我正在使用下面的代码来parsing一个string到DOM:

var doc new DOMParser().parseFromString(string, 'text/xml'); 

其中string就像<!DOCTYPE html><html><head></head><body>content</body></html>

typeof doc给我的object 。 如果我做了像doc.querySelector('body')我得到一个DOM对象。 但是,如果我尝试访问任何属性,就像你通常可以,它给了我undefined

 doc.querySelector('body').innerHTML; // undefined 

其他属性也是如此,例如id 。 另一方面,属性检索精确doc.querySelector('body').getAttribute('id');

有没有一个神奇的function来访问这些属性?

您当前的方法失败,因为没有为给定的XML文档定义HTML属性。 如果您提供text/html MIMEtypes,该方法应该工作。

 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 MIMEtypes的浏览器,它本来不支持它。 从Mozilla开发者networking中检索:

 /* * DOMParser HTML extension * 2012-02-02 * * By Eli Grey, http://eligrey.com * Public domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ /*! @source https://gist.github.com/1129031 */ /*global document, DOMParser*/ (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\/html\s*(?:;|$)/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)); 

对于XML / HTML元素使用element.getAttribute(attributeName)