LeBlaireau
LeBlaireau

Reputation: 17467

jquery reorder divs

I have 3 divs want to reverse the order on doucment ready

<div id="block-1">First</div>
<div id="block-2">Second</div>
<div id="block-3">Third</div>

How can I do this in jquery?

Upvotes: 9

Views: 32447

Answers (4)

Explosion Pills
Explosion Pills

Reputation: 191729

$(
   $("div[id|=block]")
      .slice(1)
      .get()
      .reverse()
 )
    .insertBefore("div[id|=block]:first");

http://jsfiddle.net/8adwS/

Also note that you can add the array reverse syntax to the jQuery function syntax, which would save you a selector.

Upvotes: 0

Chuck Norris
Chuck Norris

Reputation: 15190

<div id="parent">
<div id="block-1">First</div>
<div id="block-2">Second</div>
<div id="block-3">Third</div>
</div>

And try this in Jquery

$('#parent > div').each(function() {
    $(this).prependTo(this.parentNode);
});​

You can see example in jsfiddle http://jsfiddle.net/N7PGW/

Upvotes: 20

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

Just use

$('#block-2').insertBefore('#block-1');
$('#block-3').insertBefore('#block-2');

Example fiddle: http://jsfiddle.net/2DUXF/

Upvotes: 12

Shyju
Shyju

Reputation: 218722

This will reverse all divs inside a div with id "div1"

  $(function(){
    var items=$("#div1 div").toArray();
        items.reverse();
        $.each(items,function(){
           $("#div1").append(this); 
        });     
    });​

Here is the jsFiddle http://jsfiddle.net/bCAVz/8/

Upvotes: 4

Related Questions