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

89
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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