JavaScript DOMParser access innerHTML e outras propriedades
estou a usar o seguinte código para processar uma cadeia em DOM:
var doc new DOMParser().parseFromString(string, 'text/xml');
onde string
é algo como <!DOCTYPE html><html><head></head><body>content</body></html>
.
typeof doc
Dá-me. Se eu fizer algo como ... recupero um objecto DOM. Mas se eu tentar aceder a alguma propriedade, como tu normalmente consegues, dá-me undefined
:
doc.querySelector('body').innerHTML; // undefined
o mesmo se aplica a outras propriedades, por exemplo id
. A obtenção de atributos, por outro lado, vai bem doc.querySelector('body').getAttribute('id');
.
2 answers
O seu método actual falha, porque as propriedades HTML não estão definidas para o documento XML indicado. Se fornecer o tipo MIME text/html
, o método deve funcionar.
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"
O código abaixo activa o text/html
tipo MIME para navegadores que ainda não o suportam nativamente. É obtida da rede de desenvolvimento do Mozilla :
/*
* 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));
Usar element.getAttribute(attributeName)
para elementos XML / HTML