JavaScript Generated SVGs Do Not Render Content

I’m teaching myself JavaScript and SVG to create some interactive graphics for a web page, but am encountering a problem with a path not being drawn in programmatically generated SVGs. Here is a test code that exhibits the problem:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<svg width="1em" height="1em" viewBox="0 0 350 350"
     preserveAspectRatio="xMidYMid meet"
     style="border: 1px solid #cc0000;">

    <path d="M 50 50 L300 50 L300 300 L50 300 Z"/>
</svg>
</body>
<script>
"use strict";
var s = document.createElementNS("http://www.w3.org/2000/svg","svg")
s.setAttribute("width","1em")
s.setAttribute("height","1em")
s.setAttribute("viewBox", "0 0 350 350")
s.setAttribute("preserveAspectRatio","xMidYMid meet")
s.setAttribute("style","border: 1px solid #cc0000;")
var g = document.createElement("path")
g.setAttribute("d",'M 50 50 L300 50 L300 300 L50 300 Z')
s.appendChild(g)
document.body.appendChild(s)
</script>
</html>

This displays two SVGs, side-by-side, each with a red border box. However, the first one–generated from the HTML–draws a black rectangle into the SVG. The second–generated by the JavaScript code–just won’t draw the rectangle.

I cannot figure out why. Inspecting both SVGs in the rendered page’s DOM shows them to be completely identical. Yet every browser I’ve tried only draws the first rectangle.

Any advice on this surely elementary error?

21 thoughts on “JavaScript Generated SVGs Do Not Render Content”

  1. You used createElementNS for the svg element, you need to use that same function to create the path, createElement won’t do because it creates elements in the HTML namespace, not in the SVG namespace.

    var g = document.createElementNS("http://www.w3.org/2000/svg", "path")
    
    Reply

Leave a Comment