2016-04-17 29 views
1

Array.prototype.sort()を使用してDOM.Elementをソートします。JavaScript Array.prototype.sort()DOM.HTMLLIElementを呼び出すことができません

私はこのようにしてみてください:

var e = document.getElementById('test-list').children; 
 
    
 
    [].forEach.call(e,function(ee){ 
 
     console.log(ee); 
 
    }); 
 
    // print each child in e 
 
    
 
    [].sort.call([3,4,1],function(a,b){ 
 
     console.log(a+","+b); 
 
    }); 
 
    // 3,4; 4,1; [3, 4, 1]; compares every two elements 
 
    
 
    
 
    [].sort.call(e,function(a,b){ 
 
     console.log(a+","+b); 
 
    }); 
 
    // 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> 
 
    </ol>

Array.prototype.sort()のAPIの基本、sort()は、より基本的なタイプよりも、通常のオブジェクトに使用することができます。

そして私は、だから私は理由HTMLLIElementsの配列内の要素がsort()は何とかそれを考え出し、直接変更することはできないという事実を前提と

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

を見つけました。だからsort()ちょうど飛び出して戻ります。

そうですか?そして、施設が助けてsort()が配列を扱うかどうか決定するのを助けますか?

+0

この 'Array.prototype.slice.call(document.getElementById( 'test-list')。children)'のような配列に変換してみてください。 – destoryer

+0

'Array.prototype.slice.call'は[HTMLCollectionを配列に変換する最も効率的な方法]から' [] .slice.call'と同じです(http://stackoverflow.com/questions/222841/most-efficient-way -to-an-htmlcollection-to-an-array)に変換します。そしてそれは本当に同じように働いた。 – d4rkb1ue

+1

http://stackoverflow.com/questions/7059090/array-prototype-sort-call –

答えて

1

興味深い質問!黙って死ぬクロムとは異なり、最新のFirefoxはより有用である:

問題が明らかになり

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

sort試みが所定の位置にソートするので、あなたは、数値プロパティのセッターを(持っていないオブジェクトにsortを適用することはできません失敗する)。

+0

...整理する前にまず配列に変換しなければならないことを意味します。 – Fuzzyma

+0

DOM内の要素を効果的に並べ替えたいからです。私はちょうど 'dom [i] .innerText <--> dom [j] .innerText;'を使って新しいsort()を書き直して並べ替えます。 – d4rkb1ue

関連する問題