views:

32

answers:

2

I am trying to change to position of children of the body. I obviously do not understand how to do so, but I thought it would be novel if the following code would work:

var temp = $('body').children()[0];
$('body').children()[0] = $('body').children()[1];
$('body').children()[1] = temp;

Sadly for me, it does not. I have searched and found the .add() method, but I do not see how to add to the beginning of a parent/I don't know how to delete another child.

I appreciate any help.

A: 

To swap the children just use .prependTo() to stick whichever element you want at the beginning, like this:

$('body').children().eq(1).prependTo('body');

By swapping elements in the array you're just changing the elements in the jQuery object, references to the object...not really affecting them in the DOM at all.

To .prepend() an element directly that form looks like this (and is basically what the above gets transformed into):

$('body').prepend($('body').children().eq(1));
Nick Craver
Thank you for your multiple and updated answers, I do appreciate it. By the way, worked like a charm.
azadder
@azadder - Welcome :) be sure to [accept an answer](http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work) if it solves your issue :)
Nick Craver
A: 

This will change the position of 2 or more items in the body.

Basically, it just reverses the position of elements in the body.

It goes through each child of the body and adds that child to the beginning of the body. This will reverse the order and thus position of the elements in the body.

$('body').children().each(function() {
    $(this).prependTo("body");
});​

Try it out with this jsFiddle

(for 3 elements)

References:
.children()
.each()
.prependTo()

Peter Ajtai