Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda