I wanna move the element which is already loaded to a different position.
I have referred to https://stackoverflow.com/a/16127049/19743544
The
appendChild
methods adds an element to the DOM.
insertAdjacentHTML
method takes a string instead of an element, so they have to parse the string and create elements from it
I can see that both appendChild
and insertAdjacentHTML
are actually meant to create an element instead of moving the loaded element to somewehre.
In the example below, how do I move the div .apple
into the section main
before the div orange
?
const main = document.querySelector('.main'), apple = document.querySelector('.apple'), orange = document.querySelector('.orange');
<section class="main"> <div class="orange"></div> </section> <div class="apple"></div>
Use insertBefore
const main = document.querySelector('.main'),
const apple = document.querySelector('.apple'),
const orange = document.querySelector('.orange');
main.insertBefore(apple, orange);
Note that both insertBefore and appendChild (in case you want to add it in last position) will move the element if it already exists in the DOM
If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.