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

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

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

  • Bald Eagle
  • Falcon
  • Condor<
8条回答
  •  半阙折子戏
    2020-12-29 17:41

    You can also do this. It works as follows:

    • Grab all the bird list items (the
    • elements) and return them as a NodeList
    • Convert the NodeList into an an array and reverse the array (since items in arrays can be reversed, but not items in NodeLists)
    • Append each bird list item from the array into the original list container (the
        element)

      Code:

      const birdsContainer = document.getElementById("birds");
      const birdList = birds.getElementsByTagName("li");
      
      [].slice.call(birdList)
        .reverse()
        .forEach(bird => birdsContainer.appendChild(bird));
      

提交回复
热议问题