我正在尝试对 Element.prototype.children 进行填充​​,应返回HTMLCollection

有一个 window.HTMLCollection

然而

var h = new HTMLCollection();
//TypeErrror: HTMLCollection is not a constructor


var h = Object.create(HTMLCollection.prototype);
h[0] = div;
h.item(0);
// Could not convert JavaScript argument

测试Firefox 7和Chrome

除了给HTMLCollection填充代码外,还有什么方法可以与之交互?

如果您可以提出解决方案,还请提供有关this github issue的反馈

最佳答案

这是我的处理方式:

function MyHTMLCollection( arr ) {
    for ( var i = 0; i < arr.length; i += 1 ) {
        this[i] = arr[i];
    }

    // length is readonly
    Object.defineProperty( this, 'length', {
        get: function () {
            return arr.length;
        }
    });

    // a HTMLCollection is immutable
    Object.freeze( this );
}

MyHTMLCollection.prototype = {
    item: function ( i ) {
        return this[i] != null ? this[i] : null;
    },
    namedItem: function ( name ) {
        for ( var i = 0; i < this.length; i += 1 ) {
            if ( this[i].id === name || this[i].name === name ) {
                return this[i];
            }
        }
        return null;
    }
};

其中arr是一个常规数组,其中包含应该在HTMLCollection中的所有DOM元素。

待办事项 list :
  • 应该事先检查arr参数:它是数组吗?是该数组DOM元素的所有元素吗?
  • 10-01 17:42