Repositioning children in a <body> tag using jQuery

I am trying to change the position of children in the body. I obviously don’t understand how to do this, but I thought it would be new if the following code worked:

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

Unfortunately for me this is not the case. I searched and found the .add () method, but I don’t see how to add a parent to the beginning / I don’t know how to remove another child.

I appreciate any help.

+3
source share
3 answers

For sharing children, just use .prependTo()to stick with the element you want at the beginning, for example:

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

When replacing elements in an array, you simply change the elements in the jQuery object, reference the object ... in fact, do not affect them in the DOM.

.prepend() , ( ):

$('body').prepend($('body').children().eq(1));
+2

2 .

, .

body . , , .

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

jsFiddle

( )

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

+3

if you want to place the child at the specified position, which you can use before then after: jsFiddl

Literature:

each

api.jquery.com/after/

api.jquery.com/find/

api.jquery.com/children/

0
source

Source: https://habr.com/ru/post/1769885/


All Articles