2

I have a collection of divs with id of 0, 1, 2, 3, n. They are generated in php in ascending order. I want to make a button to re-arrange them so they display in descending order using jquery. I have absolutely no clue how to do this. Can anyone refer me to an article or something?

Code:

<span>
    <div id="0">...</div>
    <div id="1">...</div>
    <div id="2">...</div>
    <div id="3">...</div>
    <div id="4">...</div>
    ...
</span>

I want a button to make it:

<span>
....
    <div id="4">...</div>
    <div id="3">...</div>
    <div id="2">...</div>
    <div id="1">...</div>
    <div id="0">...</div>
</span>
Marcel
  • 1,034
  • 1
  • 17
  • 35
  • And for your specific instance of the problem: [jQuery reversing the order of child elements](http://stackoverflow.com/q/5347839/218196) – Felix Kling Jul 11 '14 at 17:22
  • Those lis didn't have ids; therefor, the code to switch the order is different. – Marcel Jul 11 '14 at 17:25
  • And yet the solution you accepted doesn't take the IDs of the `div` elements in account. So I wonder why it matters that the `li` elements don't have IDs. Of course there are multiple ways to achieve the same goal. – Felix Kling Jul 11 '14 at 17:27

2 Answers2

3

try this

$('span div').each(function() {
    $(this).insertBefore('span div:first');
});

http://jsfiddle.net/BS4g3/

Josh Lowe
  • 486
  • 3
  • 13
2

Very simple.

Suppose that you have this current HTML:

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

Using a simple jQuery reverse will result in what you need:

$($("div").slice(1).get().reverse())
   .insertBefore("div:first");

Result:

5
4
3
2
1

Check this fiddle:

http://jsfiddle.net/66QDc/

Edit:

I updated the fiddle a button to do the task:

http://jsfiddle.net/66QDc/1/

Michał Kuliński
  • 1,928
  • 3
  • 27
  • 51
gustavodidomenico
  • 4,640
  • 1
  • 34
  • 50