d4rkb1ue d4rkb1ue - 1 year ago 121
Javascript Question

JavaScript Array.prototype.sort() CAN NOT call on DOM.HTMLLIElements

I want to use

to sort DOM.Element.

I try like this:

var e = document.getElementById('test-list').children;

// print each child in e

// 3,4; 4,1; [3, 4, 1]; compares every two elements

// CAN NOT work! don't print anything.

<ol id="test-list">
<li class="lang">Scheme</li>
<li class="lang">JavaScript</li>
<li class="lang">Python</li>
<li class="lang">Ruby</li>
<li class="lang">Haskell</li>

Base on API of
can be used on normal Objects more than basic type.

And I found

e[0].innerText = 232; // <li class="lang">232</li> ;works
e[0] = "123"; //<li class="lang">232</li> ;not work

So I assumed because of the fact that elements in Array of HTMLLIElements can not be changed directly,
somehow figured it out. So
just jump out and return.

Is that right? And what's the institution helps
decide whether deal with the Array?

Answer Source

Interesting question! Unlike Chrome, which dies silently, the latest Firefox is more helpful:

TypeError: HTMLCollection doesn't have an indexed property setter for '0'

which makes the problem clear: you cannot apply sort to an object that doesn't have numeric property setters (because sort attempts to sort in place and fails).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download