Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

<ul id="birds">
  <li>Bald Eagle</li>
  <li>Falcon</li>
  <li>Condor</li>
  <li>Albatross</li>
  <li>Parrot</li>
</ul>

With plain JavaScript (not including jQuery), I would like to be able to do reverse the order of this list - so that it matches the following expected "output":

<ul id="birds">
  <li>Parrot</li>
  <li>Albatross</li>
  <li>Condor</li>
  <li>Falcon</li>
  <li>Bald Eagle</li>
</ul>

This is the JavaScript I have attempted to code, to try and achieve this goal:

var birdList = document.getElementById("birds").getElementsByTagName("li");
var birdListReverse = birdList.reverse();

for(var i = 0; i < birdList.length; i++)
{
  birdList[i] = birdListReverse[i];
}

I would think that somehow over-writing the current list items with the ones in the "reversed" list would be sufficient, but not to be. Would I have to somehow manipulate each nodeValue in the list?

I would like to do this when a button is clicked - that is the easy part, it is just getting the technique to reverse the list that has hampered me a bit.

like image 533
Rob Avatar asked Sep 21 '12 23:09

Rob


2 Answers

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.

like image 184
Neil Avatar answered Sep 27 '22 18:09

Neil


var birds = document.getElementById('birds');

for(var i = 0, bll = birds.childNodes.length; i < bll; i++) {
  birds.insertBefore(birds.childNodes[i], birds.firstChild);
}
like image 29
Brett Zamir Avatar answered Sep 27 '22 19:09

Brett Zamir