create a HTMLCollection

最后都变了- 提交于 2019-11-26 14:48:48

问题


I'm trying to shim Element.prototype.children which should return a HTMLCollection

There is a window.HTMLCollection

However

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

and

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

Test Firefox 7 and Chrome

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

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


回答1:


Here's how I would do it:

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;
    }
};

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

To do list:

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



回答2:


Don't expect host objects to behave like (ECMAScript) native objects, they are completely different things. Some browsers do implement their DOM objects like ECMAScript objects, but it is not required and should not be relied upon. Note that most HTML collections are live, it is very difficult to emulate that in a native object.




回答3:


I know this is an older question but I came across a similar need to create an empty HTMLCollection and I did it by simply creating an element and then running getElementsByClassName() against it using a class that doesn't exist in the element.

document.createElement("div").getElementsByClassName('noClassHere');

This returns an empty HTMLCollection object.



来源:https://stackoverflow.com/questions/7754269/create-a-htmlcollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!