The problem is you’re not working with a Array
, but rather with a NodeList
. Methods such as the getElementsByClassName
or the querySelectorAll
do not return an array, but rather a collection of DOM elements. This collection is called NodeList
and is a different object from Array
(and therefore does not implement all methods of "conventional arrays", such as the sort
, filter
, map
, etc.).
In this sense, as the method sort
is implemented in the prototype of Array
, one option is to convert your NodeList
to an array before using it. Below I show some options for this.
Like NodeList
implements the language iteration protocol, you can use the scattering operator to convert it into a Array
:
[...letterDivs].sort((a, b) => /* ... */);
In the above example, [...letterDivs]
is an expression that evaluates to an array. So we can use sort
afterward.
Another option is to use Array.from
, which also returns an array:
Array.from(letterDivs).sort((a, b) => /* ... */);
One observation is that the two above formats return an array. So, the expression does not return one NodeList
, but rather a Array
.
You might consider using Function.prototype.call
or Function.prototype.apply
, but as the method Array.prototype.sort
does not copy the this
(which is usually an original array), modifications are made to the given value itself as argument this
.
So if you use a NodeList
as this
of sort
, may end up getting an error like "Failed to set an Indexed Property". Can end up modifying the GIFT unintentionally as well, since NodeList
is a "live list".
But when I do a console.log of letterDivs after Sort returns me a nodelist. Why?
– Inês Barata Feio Borges
Hmm, it’s true. I edited the answer. :)
– Luiz Felipe