create a HTMLCollection

Raynos picture Raynos · Oct 13, 2011 · Viewed 13k times · Source

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

Answer

Alex Szücs picture Alex Szücs · Nov 28, 2019

I think this is the proper way of creating HTMLCollection, which is handled by the browser.

var docFragment = document.createDocumentFragment();
docFragment.appendChild(node1);
docFragment.appendChild(node2);
var myHTMLCollection = docFragment.children;

Refs.:

https://stackoverflow.com/a/35969890/10018427

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