Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
A new SVG created from the DOM it doesn't display by using document.body.appendChild(<svgId_or_svgVariable>)

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:

  • I'm sure that there're plenty of ways to do the same but in this case, I'm using pure JS for a few SVG.
  • In the link to the thread that I prior wrote there's an answer that recommends using d3 library to manage SVG.
  • As the docs state: Warning: cloneNode() may lead to duplicate element IDs in a document! and name could be duplicated as well.
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!