How to swap a div of place with script?

Asked

Viewed 31 times

1

For example I have on the page:

<div class="geral"></div>

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

<div class="geral-2"></div>

How to put the second DIV under the first one with script thus staying?

<div class="geral"></div>
<div class="geral-2"></div>

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ps: I don’t have access to base code so you need to move using script.

1 answer

2


You can "copy" the div geral-2 with a outerHTML define or return the HTML element and all its contents, including the initial tag, its attributes and the final tag. Then remove the old geral-2 and with a insertAdjacentHTML you insert the copied after the div geral.

var geral1 = document.querySelector('.geral')
var geral2 = document.querySelector('.geral-2')
var copy = geral2.outerHTML
geral2.remove()

geral1.insertAdjacentHTML('afterend', copy)

console.log(document.body.innerHTML)
<div class="geral"></div>

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

<div class="geral-2"></div>

I hope I’ve helped.

About insertAdjecentHTML if you don’t know it insertAdjacentHTML - MDN

Browser other questions tagged

You are not signed in. Login or sign up in order to post.