This website collects cookies to deliver better user experience
Moving a static HTML element into a dynamically created element with JavaScript.
Moving a static HTML element into a dynamically created element with JavaScript.
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.
I was coding all of this out in Javascript, using ALOT of
document.createElement// Practicing my DOM skills :)
When it came time to recreate the SVG in JavaScript, it became a bit much. Especially since I had six to do.
Solution
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;}
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