Remove element then add it inside another element in Javascript

677 Views Asked by At

I would like to remove a <script> tag inside a <div> and add it to another <div>.

In jQuery it would be:

$('.scripts').remove().appendTo('.another-container');

It works fine in jQuery, but I would prefer to use the plain javascript method than the jQuery one. Therefore I'm trying to write in JS but it doesn't work:

const scriptTag = document.querySelector(".scripts");
const container = document.querySelector(".another-container");

for (var i = 0; i < scriptTag.length; i++) {
    scriptTag[i].parentNode.removeChild(scriptTag[i]);
    container.appendChild(scriptTag[i]);
}

Thank you.

3

There are 3 best solutions below

0
grimsteel On

I don't have enough reputation to comment but document.querySelector doesn't return an array. (querySelectorAll does)

const scriptTag = document.querySelector(".scripts");
const container = document.querySelector(".another-container");

scriptTag.parentNode.removeChild(scriptTag);
container.appendChild(scriptTag);

However, because nodes can only exist in one place at a time, it would be more concise to just directly append the script tag to the container

const scriptTag = document.querySelector(".scripts");
const container = document.querySelector(".another-container");

container.appendChild(scriptTag); // This will automatically remove scriptTag from its original parent
0
Ali Dadashi On

You dont need to remove the element. It will be removed automatically.

const scriptTag = document.querySelector(".scripts");
const container = document.querySelector(".another-container");
container.appendChild(scriptTag);

Plus, document.querySelector() doesn't return an array. So there is no need to for loop.

0
Codin Plus On

You must get scriptTag element with querySelectorAll before you use for loop if not it wouldn't work example

const scriptTag = document.querySelectorAll(".scripts");
const container = document.querySelector(".another-container");
for (var i = 0; i < scriptTag.length; i++) {
container.appendChild(scriptTag[i]);
scriptTag[i].parentNode.removeChild(scriptTag[i]);
}