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 fo开发者_JAVA百科llowing 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.
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));
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()
if you want to put children element into specified position you can use before,after like this:
jsFiddl
References:
each
api.jquery.com/after/
api.jquery.com/find/
api.jquery.com/children/
精彩评论