HTMLDocument和XMLDocument 的children

在全部主流瀏覽器中,document是一個HTMLDocument類型的對象。javascript

document.children  或者 DOM元素的children都是能夠訪問的,它返回是該節點下的全部Element節點。 它們一樣還有一個childNodes屬性,它返回全部節點,區別就是它包含全部文字節點,註釋節點等等,它通常比 children返回的元素多。html

console.dir(document.__proto__)
    HTMLDocument
console.dir(document.body.__proto__)
    HTMLBodyElement 
document.children
    [html]
document.childNodes
   (2) [<!DOCTYPE html>, html]
document.body.children
  (2) [div#main, div.timeTravel]
document.body.childNodes
  (4) [text, div#main, text, div.timeTravel]java

IE11下,解析一個XML文件後,獲得的對象是XMLDocument,它居然沒有children屬性。而chrome,firefox都是有children屬性的。node

var parser = new DOMParser();
var root = parser.parseFromString(this.xbrl, "application/xml");   //root 是XMLDocument對象

去MDN上查詢一下XMLDocument的API,居然說chrome

W3C並無定義XMLDocument接口。緣由是document接口原本就是爲xml定義的。而HTML只是xml的一種實現。瀏覽器

如今來看,就IE瀏覽器解析的XMLDocument有問題!爲了保證代碼用children屬性,給這兩個原型增長children,我是這樣解決的:app

var parser = new DOMParser();
var root = parser.parseFromString(this.xbrl, "application/xml");
    //IE11中,root是XMLDocument對象,沒有  children屬性
if (!root.children) {
    Object.defineProperty(XMLDocument.prototype, "children", {
        get: function () {
            var nodes=Array.prototype.slice.call( this.childNodes) as Node[];
            return nodes.filter((n)=>n.nodeType==1);
        }
    });
    Object.defineProperty(Element.prototype, "children", {
        get: function () {
            var nodes=Array.prototype.slice.call( this.childNodes) as Node[];
            return nodes.filter((n)=>n.nodeType==1);
        }
    });
}
//此處便可用children來獲取子節點了,
this.xbrlHtml = this.renderElement(root.children[0]);

完美解決!this

相關文章
相關標籤/搜索