javascript - ie11 Element.children 填充

标签 javascript

我正在开发一个项目,其中我将 es6 代码与 babel 结合使用。 我使用以下代码:

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

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

由于没有children属性,它在IE11上不起作用的问题。

我创建了以下polyfill,但没有帮助:

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时,我可以看到原型(prototype)是Element,但属性没有添加。另外使用时:

selectorResult instanceof Element
selectorResult instanceof Node

我对这两点都错了。

目前,我使用一种方法来提取子项,而不是添加到原型(prototype)中,这是我更喜欢的。

有什么建议吗?

提前致谢

最佳答案

以下代码将属性 children 添加到所有 HTML、XML 和 SVG 元素 - 刚刚在 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 上找到了这个 polyfill。

这个polyfill将返回一个数组,而不是一个HTMLCollection,但您仍然可以使用Node.children.lengthNode.children[索引]

使用这个polyfill,你可以像这样迭代你的结果:

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

关于javascript - ie11 Element.children 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41847901/

相关文章:

javascript - 使用导入/导出默认语法从存储库导入文件时 Jest 失败

Javascript:为什么命名对象方法函数

javascript - 使用键盘快捷键打开 Chrome 扩展程序弹出窗口?

javascript - 控制台中出现不兼容的 IE 文档模式错误?

javascript - 在加载时执行匿名函数,然后使用 setTimeout 每 30 秒再次执行一次

javascript - Javascript 数字加法给出错误答案

javascript - .change() 函数不起作用

javascript - 当使用多种编码时如何分离 json 解析的数据?

javascript - 如何使 javascript 与使用 ajax 加载的 htm 一起工作

javascript - 焦点改变时保持文本选择