Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda