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

前端 未结 8 1026
独厮守ぢ
独厮守ぢ 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
    var birds = document.getElementById('birds');
    
    for(var i = 0, bll = birds.childNodes.length; i < bll; i++) {
      birds.insertBefore(birds.childNodes[i], birds.firstChild);
    }
    
    0 讨论(0)
  • 2020-12-29 17:41

    You can also do this. It works as follows:

    • Grab all the bird list items (the <li> 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 <ul> element)

    Code:

    const birdsContainer = document.getElementById("birds");
    const birdList = birds.getElementsByTagName("li");
    
    [].slice.call(birdList)
      .reverse()
      .forEach(bird => birdsContainer.appendChild(bird));
    
    0 讨论(0)
提交回复
热议问题