7 February 2024

In this snippet we move/clone dom elements with all children for later usage.

The JavaScript code directly interacts with the HTML document's elements, specifically targeting two divs identified by their IDs: 'sourceDiv' and 'destinationDiv'. Through a while loop, the code continuously moves the first child element of sourceDiv to destinationDiv, until sourceDiv no longer has any child elements remaining. This process is executed solely through DOM manipulation, demonstrating a direct approach to element traversal and modification without the use of wrapper functions or additional abstractions.

Moving does not loose events. If you where to clone the dom, it would loose all attached events. You can even move them to hidden div if you don't want to show the elements for a while.

Source code viewer
  1. var sourceDiv = document.getElementById('sourceDiv');
  2. var destinationDiv = document.getElementById('destinationDiv');
  4. // Using a while loop to move elements to the destination div
  5. while (sourceDiv.firstElementChild) {
  6. destinationDiv.appendChild(sourceDiv.firstElementChild);
  7. }
Programming Language: Javascript