Using Array.prototype.sort.call to sort a HTMLCollection

后端 未结 3 1325
闹比i
闹比i 2020-12-17 05:05
var down=function(a,b){alert(a)}
Array.prototype.sort.call(table.tBodies[0].childNodes,down)
Array.prototype.sort.call([0,1,2,3],down)

Why do I not

相关标签:
3条回答
  • 2020-12-17 05:27

    I correct the code of gaetanoM, this one works with IE :

    window.onload = function() {
      var parentNode = document.getElementById('test-list');
      var e = document.getElementById('test-list').children;
      [].slice.call(e).sort(function(a, b) {
      	if (a.textContent > b.textContent) return 1;
      if (a.textContent < b.textContent) return -1;
      return 0;
       }).forEach(function(val) {
        parentNode.appendChild(val);
      });
    }
    <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>
        <li class="lang">Tata</li>
        <li class="lang">Aaaaa</li>
        <li class="lang">Drue</li>
    </ol>

    0 讨论(0)
  • 2020-12-17 05:31

    Convert the NodeList to an array first:

    var elements = [].slice.call(table.tBodies[0].childNodes);
    

    and then call sort normally:

    elements.sort(down);
    

    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.

    0 讨论(0)
  • 2020-12-17 05:40

    My proposal to sort an HTMLCollection is:

    window.onload = function() {
      var parentNode = document.getElementById('test-list');
      var e = document.getElementById('test-list').children;
      [].slice.call(e).sort(function(a, b) {
        return a.textContent.localeCompare(b.textContent);
      }).forEach(function(val, index) {
        parentNode.appendChild(val);
      });
    }
    <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>

    0 讨论(0)
提交回复
热议问题