DEV Community

loading...

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

ZediWards
Learning the fundamentals of HTML, CSS, and JavaScript. Trying my hand at writing about the core concepts of a topic while trying not to get caught up in the weeds.
・2 min read

Context:

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.
tank-1-modal

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.

Solution

Component 1

HTML & CSS

  • 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

JavaScript

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];
svgLocationTarget.appendChild(svg);
svg.classList.remove("hidden");
Enter fullscreen mode Exit fullscreen mode

TADA!!!

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.

Discussion (0)