views:

36

answers:

2

Input:

<content>
   <dom id=1>a</dom>
   <dom id=2>b</dom>
   <dom id=3>c</dom>
   <dom id=4>d</dom>
</content>

Output:

<content>
   <dom id=4>d</dom>
   <dom id=3>c</dom>
   <dom id=2>b</dom>
   <dom id=1>a</dom>
</content>

I'm looking for a function (if exists) like this:

$('content').inverse();

+2  A: 

Use jQuery Reverse Order plugin

jQuery Reverse Order uses jQuery to reverse the order of DOM elements on your page.

Example:

$('#items p').reverseOrder();

The plugin is quite simple:

(function($) {
    $.fn.reverseOrder = function() {
        return this.each(function() {
            $(this).prependTo( $(this).parent() );
        });
    };
})(jQuery);

Try it out with this jsFiddle

SDReyes
+3  A: 

Something like this would work:

$(​$("content dom").get().reverse()).appendTo("content");​​​​​​​​

You can test it out here, or if you like the reverse flavor:

$("content").append($("content dom").get().reverse());​

Try that version here.

Nick Craver
As a plugin ==> http://jsfiddle.net/DmgaN/
Peter Ajtai
You can compare the performance at http://jsperf.com/dom-node-reversal. **Note:** Neither of the versions shown above works if there are multiple 'content' nodes on the page. The http://plugins.jquery.com/project/reverseorder plugin mentioned in the other answer works best, but is the slowest.
Dan Manastireanu
I like to use CORE functions of jQuery as well as possible, no plugins, this answer is what I want
Cris Hong Kong CRISHK