How to reverse the ordering of list items in an unordered list

前端 未结 8 1064
独厮守ぢ
独厮守ぢ 2020-12-29 17:06

Let\'s say I have an unordered list, like this:

  • Bald Eagle
  • Falcon
  • Condor<
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 17:24

    An HTMLCollection is only a read-only view of nodes. In order to manipulate nodes, you have to use one of the various DOM manipulation methods. In your case, there happens to be a shortcut; all you need do is to append the child nodes in reverse order.

    var birds = document.getElementById("birds");
    var i = birds.childNodes.length;
    while (i--)
      birds.appendChild(birds.childNodes[i]);
    

    Edit: What's happening is that appendChild removes the node from the document before appending it. This has two effects: a) it saves you from having to make a copy of the list of nodes and removing them before appending them in reverse order, and b) it reverses the order of nodes as it goes, since it appends the last child first and the first child list.

提交回复
热议问题