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

83
Visualizações
SVG appended to DOM with JS but not visually rendering

I'm trying to create an SVG shape and append it to an element in my DOM.

The following JS appends the <svg> to the intended node, but doesn't render a purple background on the page:

const svgBox = document.createElement("svg");
svgBox.setAttribute('height', 150);
svgBox.setAttribute('width', 800);
svgBox.setAttribute('style', 'background-color:purple;');
const div = document.getElementsByTagName('div')[0];  // this does exist
div.appendChild(svgBox);

Here is a JSFiddle showing the equivalent HTML that does work (if I comment the tag back in) but the above JS not working. I've stripped this down from a more complex use case and have demonstrated to myself I'm missing some crucial basic display principle.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

An SVG is a namespaced element, so you have to use createElementNS instead of createElement - to understand why check out this answer

Here is a working example:

const svgBox = document.createElementNS("http://www.w3.org/2000/svg", "svg");

svgBox.setAttribute('height', 150);
svgBox.setAttribute('width', 800);
svgBox.setAttribute('style', 'background-color:purple;');

const div = document.getElementsByTagName('div')[0]; // this does exist
div.appendChild(svgBox);
<div>
</div>


about 4 years ago · Juan Pablo Isaza Relatório
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