JavaScript DOMParser访问innerHTML等属性 [英] JavaScript DOMParser access innerHTML and other properties

查看:134
本文介绍了JavaScript DOMParser访问innerHTML等属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来将字符串解析为DOM:

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

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

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

  doc.querySelector( '主体')的innerHTML。 // undefined 

其他属性也是如此。 ID 。另一方面,属性检索变得很好 doc.querySelector('body')。getAttribute('id');



是否有一个魔术功能来访问这些属性?

解决方案

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

  var string ='<!DOCTYPE html>< html>< head>< / head>< body> content< / body>< / html>'; 
var doc = new DOMParser()。parseFromString(string,'text / html');
doc.body.innerHTML; //或doc.querySelector('body')。innerHTML
// ^返回内容

下面的代码为不支持本身的浏览器使用 text / html MIME类型。从 Mozilla开发人员网络检索:

  / * 
* DOMParser HTML扩展
* 2012-02-02
*
*由Eli Gray,http://eligrey.com
*公共领域。
*无明示或暗示的保证。使用您自己的风险。
* /

/ *! @source https://gist.github.com/1129031 * /
/ *全局文件,DOMParser * /

(function(DOMParser){
use strict;
var DOMParser_proto = DOMParser.prototype
,real_parseFromString = DOMParser_proto.parseFromString;

// Firefox / Opera / IE在不支持的类型上抛出错误
try {
// WebKit在不支持的类型上返回null
if((new DOMParser).parseFromString(,text / html)){
// text / html解析本身支持
返回;
}
} catch(ex){}

DOMParser_proto.parseFromString = function(标记,类型){
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));


I am using the following code to parse a string into DOM:

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

Where string is just something like <!DOCTYPE html><html><head></head><body>content</body></html>.

typeof docgives me object. If I do something like doc.querySelector('body') I get a DOM object back. But if I try to access any properties, like you normally can, it gives me undefined:

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

The same goes for other properties, e.g. id. The attribute retrieval on the other hand goes fine doc.querySelector('body').getAttribute('id');.

Is there a magic function to have access to those properties?

解决方案

Your current method fails, because HTML properties are not defined for the given XML document. If you supply the text/html MIME-type, the method should work.

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"

The code below enables the text/html MIME-type for browsers which do not natively support it yet. Is retrieved from the Mozilla Developer Network:

/* 
 * 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));

这篇关于JavaScript DOMParser访问innerHTML等属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆