创建一个HTMLCollection [英] create a HTMLCollection

查看:129
本文介绍了创建一个HTMLCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在加快 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

Test Firefox 7 and Chrome

除了垫片 HTMLCollection 是否有任何方式与之进行互动?

Apart from shimming HTMLCollection is there any way to interact with it?

另请提供有关此github问题的反馈意见,如果您可以提出解决方案

Also provide feedback on this github issue if you can suggest a solution

推荐答案

我将如何做:

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 是一个常规数组,包含所有DOM元素应该在HTMLCollection内。

where arr is a regular array that contains all the DOM elements which should be inside the HTMLCollection.

要做列表:


  • 参数 arr 应该事先检查:是数组吗?所有这些数组的元素都是DOM元素?

  • the argument arr should be checked beforehand: Is it an array? Are all elements of that array DOM elements?

这篇关于创建一个HTMLCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆