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

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

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

  • Bald Eagle
  • Falcon
  • Condor<
8条回答
  •  旧时难觅i
    2020-12-29 17:40

    You can do it like this (in plain javascript). You can just cycle through the li tags in reverse order and append them to the parent. This will have the natural effect of reversing their order. You get the last one, append it to the end of the list, get the 2nd to last one, append it to the list. Get the 3rd to last one, append it to the end of the list and so on and all the items end up reversed. Note, you can use appendChild on something that is already in the DOM and it will be moved from it's current location automatically (e.g. removed before appended).

    var birds = document.getElementById("birds");
    var birdList = birds.getElementsByTagName("li");
    for (var i = birdList.length - 1; i >= 0; i--) {
        birds.appendChild(birdList[i]);
    }​
    

    Working example: http://jsfiddle.net/jfriend00/GLvxV/

提交回复
热议问题