I wanna move the element which is already loaded to a different position.
I have referred to https://stackoverflow.com/a/16127049/19743544
The
appendChildmethods adds an element to the DOM.
insertAdjacentHTMLmethod takes a string instead of an element, so they have to parse the string and create elements from it
I can see that both appendChildand 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.