Reputation: 7372
I'm working on a project in which I use es6 code with babel. I use the following code:
let result= xmlDocument.querySelector("xmlNodeSelector");
for (let child of result.children) { /* do something */ }
The problem it doens't work on IE11 since no children property.
I create the following polyfill but it didn't help:
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;
}
});
When I debug IE11 I can see the prototype is Element but the property is not added. In addition when using:
selectorResult instanceof Element
selectorResult instanceof Node
I get false on both.
At the moment I use a method to extract children rather then adding to the prototype which is what i prefer.
Any suggestions?
Thanks in advance
Upvotes: 1
Views: 1588
Reputation: 189
The following code adds the property children
to all HTML,XML and SVG elements - just tested it under 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);
I found that polyfill on MDN.
This polyfill will return an array
, instead of an HTMLCollection
, but you can still make use of Node.children.length
and Node.children[index]
.
Using this polyfill you could iterate your result like this:
var resChildren = result.children
var index, maxindex;
for (index=0, maxindex=resChildren.length; index<maxindex; index++)
{
/* do_something_with(resChildren[index]); */
}
Upvotes: 2