2017-01-25 16 views
1

私はバベルでes6コードを使用するプロジェクトに取り組んでいます。ie11 Element.children polyfill

let result= xmlDocument.querySelector("xmlNodeSelector"); 

for (let child of result.children) { /* do something */ } 

それは子供がいないプロパティので、IE11で作業doens't問題: 私は、次のコードを使用します。

私は、次のポリフィルを作成するが、それは助けていませんでした:

if(Element.prototype.hasOwnProperty('children')){ 
      return; 
     } 

     Object.defineProperty(Element.prototype, 'children', { 
      get: function(){ 

       let children = new HTMLCollection(); 

       for(let i=0; i < this.childNodes.length; i++){ 
        let item = this.childNodes[i]; 

        if(item.nodeName !== '#text'){ 
         children.push(item); 
        } 
       } 

       return children; 
      } 
     }); 

私はIE11をデバッグするとき、私はプロトタイプは要素ですが、プロパティが追加されていない見ることができます。加えて、使用する場合:

selectorResult instanceof Element 
selectorResult instanceof Node 

私は両方でfalseになります。

現時点では、私が好むプロトタイプを追加するのではなく、子供を抽出する方法を使用します。

提案がありますか?

事前

+0

あなたは '<>'ボタンをクリックして、[MCVE] – mplungjan

+0

は前に多くのコードを追加して追加してくださいすることができため...ループ –

+0

IE11の子要素を持ちますが、html要素のみです。これは、あなたがpolyfillが役に立たない理由です。 – Arnial

答えて

1

のおかげで、次のコードは、すべてのHTML、XMLやSVG要素にプロパティchildrenを追加するには - ちょうどIE11の下でそれをテストした:

//make sure we have Node.children and Element.children available 
(function (constructor) { 
    if (constructor && 
     constructor.prototype && 
     constructor.prototype.children == null) { 
     Object.defineProperty(constructor.prototype, 'children', { 
      get: function() { 
       var i = 0, node, nodes = this.childNodes, children = []; 
       //iterate all childNodes 
       while (node = nodes[i++]) { 
        //remenber those, that are Node.ELEMENT_NODE (1) 
        if (node.nodeType === 1) { children.push(node); } 
       } 
       return children; 
      } 
     }); 
    } 
    //apply the fix to all HTMLElements (window.Element) and to SVG/XML (window.Node) 
})(window.Node || window.Element); 

を私はMDNにそのポリフィルを発見しました。

このポリフィルではなくHTMLCollectionの、arrayを返しますが、あなたはまだNode.children.lengthNode.children[index]を利用することができます。あなたはこのようなあなたの結果を反復処理することができ、このポリフィルを使用

var resChildren = result.children 
var index, maxindex; 
for (index=0, maxindex=resChildren.length; index<maxindex; index++) 
{ 
    /* do_something_with(resChildren[index]); */ 
}