Gert Cuykens Gert Cuykens - 11 months ago 218
Javascript Question

Using to sort a HTMLCollection

var down=function(a,b){alert(a)}[0].childNodes,down)[0,1,2,3],down)

Why do I not get alerts from the first sort call?


Convert the NodeList to an array first:

var elements = [][0].childNodes);

and then call sort normally:


It seems sort cannot handle array-like objects. This is probably because NodeList does not provide any methods to change the list, but sort sorts the array in-place.

Update: For more information, from the specification:

Perform an implementation-dependent sequence of calls to the [[Get]] , [[Put]], and [[Delete]] internal methods of obj.

I assume NodeLists don't have these internal methods. But this is really just an assumption. It could also be that this is implementation dependent.

I also suggest you use .children [MDN] instead of .childNodes to only get element nodes. Update: Or .rows [DOM Spec] as @patrick suggests.