DEV Community


Posted on

Moving a static HTML element into a dynamically created element with JavaScript.


I was building a series of modals that open separately when their corresponding button was clicked. Each modal was split in two parts. The left side was a SVG of a tank, and the right, a form with some inputs and a update button.

The tank's SVG fill gradient would change depending on the inputs entered in the form to its right.

I was coding all of this out in Javascript, using ALOT of

document.createElement // Practicing my DOM skills :)
Enter fullscreen mode Exit fullscreen mode

When it came time to recreate the SVG in JavaScript, it became a bit much. Especially since I had six to do.


Component 1


  • Code the SVG inside the HTML parent that the dynamically created modal will be appended to later.
    • The SVG being placed inside the modals parent will make it easier to traverse the DOM later and place it inside the modal.
  • Add a CSS class of hidden to the SVG element.
.hidden {
  display: none;
Enter fullscreen mode Exit fullscreen mode


On the lines after I created the modal

  • Grab the SVG by its class name
  • Grab the element that will be the SVGs new parent
    • target it by traversing the DOM in relation to the SVG elements current location
  • Append the SVG to the new parent
  • Remove the hidden class
const svg = document.querySelector(`svg-tank-1`);
const svgLocationTarget = svg.nextElementSibling.children[2].children[0].children[1];
Enter fullscreen mode Exit fullscreen mode


I took a hard coded HTML element and relocated it inside a dynamically created element. Then I made it visible by removing the "hidden" class name.

Top comments (0)