0

I create this question in order to quickly find this specific solution but I guess the answer is the same for this kind of issue.

Problem

I created an SVG from the DOM and I wanted to append it to the body (or anywhere) but I couldn't see it displayed on the web even when I could find it listed in the DOM tree in the console and if I copied the element from the console and pasted into the HTML it was giving to me the expected outcome.

Solution

I was using document.createElement instead of document.createElementNS to create my SVG.

This second one creates an element with the specified namespace URI and qualified name.

See the main answer here:

Add SVG element to existing SVG using DOM

    // Get the references that you want to copy
    const svg1 = document.getElementById('svg1');
    const path1 = document.getElementById('path1');

    //Here I was using: document.createElement('svg') instead of this:
    const svg2 = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    
    // Set some svg attributes
    svg2.id = 'svg2';
    svg2.setAttribute('viewBox','0 0 1200 1200');
    
    // Clone the original path and append to the new svg
    const cpath2 = path1.cloneNode();
    cpath2.id = 'cpath2';
    svg2.appendChild(cpath2);

    // Finally append created svg to wherever you want  
    document.body.appendChild(svg2);

PD: about copying from an existing SVG:

Jony
  • 11
  • 2
  • 1
    If I understand you correctly, the above is not meant to be a question, but a question and an immediate answer. Please read [Can I answer my own question?](https://stackoverflow.com/help/self-answer) for how to go about that. – ccprog Feb 01 '22 at 18:28

0 Answers0