Using A NodeList as an Array
The Scenario:
I had queried a bunch of tags, using querySelectorAll(), and received a NodeList i...
For further actions, you may consider blocking this person and/or reporting abuse
I like this solution. Only very recently I came across this problem myself as well (I mainly only do back end), and I solved it through
[].forEach.call(NodeListHere, function () {})as I didn't want to change original object.There are some issues in this article. I can guess some of those come from the notation you've used?
That's correct for
mapandfilter, butforEachhas now been added toNodeList.prototype.It won't. Elements in a
NodeListare objects of classNode, and that's what matters, becausecompareDocumentPositionis defined in the prototype of theNodeclass. The classNodeListItemdoesn't exist in JavaScript, and anyway spreading the node list into an array, or usingArray.fromon it, won't change the class of its items: they will still beNodeinstances.The question remain, here: why do you need a
NodeListfor? In all my career, when I needed it, I've always been happy to have an array instead, back when in ES3 I had to do this:That won't work. First, it's just
Array, whileObject.Arraydoesn't exist. Then, asArrayis just a constructor, it's the methods fromArray.prototypethat you'd probably want. But then again,Object.assigncopies the properties from the source to the destination object, but only the enumerable ones. Now,map,filterand all the others are not enumerable, so your node list won't get any additional property.Moreover, there's another concern here. Even if you do copy a method like
mapto your node list, like this:The object returned by
mapwould not be aNodeList, but anArray. (That makes a lot of sense, as you could get a list of whatever you want withmap, but aNodeListis purely a list of... nodes.)Other methods like
pushorsplicemodify the source object itself, butNodeList's are immutable in JavaScript so those methods would throw aTypeError.One way to actually have the methods from arrays in a node list, and have it still as an instance of
NodeList, is to replace its prototype:But this, of course, is not object composition, and it's also generally frowned upon as mutating an object's prototype has quite some overhead.