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>
<meta charset="UTF-8">
<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"/>
"use strict";
var s = document.createElementNS("","svg")
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')

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?

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

Leave a Comment