Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  191] [ 1]  / answers: 1 / hits: 15955  / 13 Years ago, thu, october 13, 2011, 12:00:00

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


More From » dom

 Answers
13

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?


[#89630] Wednesday, October 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aricl

Total Points: 215
Total Questions: 91
Total Answers: 94

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;