我正在尝试填充应该返回HTMLCollection的Element.prototype.children
然而,
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的反馈
发布于 2011-10-13 21:18:48
下面是我会怎么做:
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元素。
待办事项列表:
arr应该事先检查:它是一个数组吗?该数组的所有元素都是DOM元素吗?发布于 2019-11-29 00:01:39
我认为这是创建HTMLCollection的正确方式,它由浏览器处理。
var docFragment = document.createDocumentFragment();
docFragment.appendChild(node1);
docFragment.appendChild(node2);
var myHTMLCollection = docFragment.children;参考文献:
https://developer.mozilla.org/en-US/docs/Web/API/NodeList
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
发布于 2011-10-13 20:53:18
不要期望宿主对象的行为像(ECMAScript)原生对象,它们是完全不同的东西。有些浏览器确实实现了它们的DOM对象,比如ECMAScript对象,但这不是必需的,也不应该依赖。请注意,大多数HTML集合都是实时的,因此很难在本机对象中模拟它。
https://stackoverflow.com/questions/7754269
复制相似问题