Sometimes, we want to move an element into another element with JavaScript.
In this article, we’ll look at how to move an element into another element with JavaScript.
How to move an element into another element with JavaScript?
To move an element into another element with JavaScript, we can use a fragment.
For instance, we write
const fragment = document.createDocumentFragment();
fragment.appendChild(document.getElementById("source"));
document.getElementById("destination").appendChild(fragment);
to call createDocumentFragment to create a document fragment.
Then we call fragment.appendChild to append an element as the last child of the fragment.
Then we use
document.getElementById("destination").appendChild(fragment)
to append the fragment to the element with ID destination.
Conclusion
To move an element into another element with JavaScript, we can use a fragment.