28
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.
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.
- 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;
}
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");
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.
28