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

82
Views
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 answers
Answer question

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 Report
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!