Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse order of a set of HTML elements

I have a set of divs that looks like this:

<div id="con">
    <div> 1 </div>
    <div> 2 </div>
    <div> 3 </div>
    <div> 4 </div>
    <div> 5 </div>
</div>

But I want them to flip so that it looks like this:

<div> 5 </div>
<div> 4 </div>
<div> 3 </div>
<div> 2 </div>
<div> 1 </div>

So that when a new <div> is added it goes to the end of the list.

How can I do this (or is there a better way of doing this)?

like image 950
user1020293 Avatar asked Oct 30 '11 01:10

user1020293


People also ask

How do you reverse the order of HTML elements?

row-reverse displays the elements in reverse order horizontally, while column-reverse displays the elements in reverse order vertically.


2 Answers

A vanilla JS solution:

function reverseChildren(parent) {
    for (var i = 1; i < parent.childNodes.length; i++){
        parent.insertBefore(parent.childNodes[i], parent.firstChild);
    }
}
like image 74
Ayman Abdel-Rahman Avatar answered Oct 20 '22 05:10

Ayman Abdel-Rahman


Wrapped up as a nice jQuery function available on any set of selections:

$.fn.reverseChildren = function() {
  return this.each(function(){
    var $this = $(this);
    $this.children().each(function(){ $this.prepend(this) });
  });
};
$('#con').reverseChildren();

Proof: http://jsfiddle.net/R4t4X/1/

Edit: fixed to support arbitrary jQuery selections

like image 28
Phrogz Avatar answered Oct 20 '22 03:10

Phrogz