创建一个HTMLCollection

Ray*_*nos 9 javascript dom dom4

我正在尝试垫片Element.prototype.children,它应该返回一个HTMLCollection

有一个 window.HTMLCollection

然而

var h = new HTMLCollection();
//TypeErrror: HTMLCollection is not a constructor
Run Code Online (Sandbox Code Playgroud)

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

测试Firefox 7和Chrome

除了垫片之外HTMLCollection还有什么方法可以与之互动吗?

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

Ale*_*ücs 8

我认为这是创建由浏览器处理的 HTMLCollection 的正确方法。

var docFragment = document.createDocumentFragment();
docFragment.appendChild(node1);
docFragment.appendChild(node2);
var myHTMLCollection = docFragment.children;
Run Code Online (Sandbox Code Playgroud)

参考:

/sf/answers/2517892331/

https://developer.mozilla.org/en-US/docs/Web/API/NodeList

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

https://www.w3schools.com/js/js_htmldom_nodelist.asp

  • DocumentFragment 必须确保其子级与先前的父级分离,因此不是 HTMLCollection 的对应部分。 (2认同)

Rob*_*obG 5

不要指望主机对象的行为类似于(ECMAScript)本机对象,它们是完全不同的东西.有些浏览器确实实现了像ECMAScript对象这样的DOM对象,但它不是必需的,不应该依赖它们.请注意,大多数HTML集合都是实时的,很难在本机对象中模拟它.


Šim*_*das 5

这是我的处理方式:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

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

待办事项清单:

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