Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Create An SVG With JavaScript

This is the basic approach for adding an SVG to a page via JavaScript. Note that `document.createElementNS`` is used instead of `document.createElement()``

HTML

<div class="exampleWrapper"></div>

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  const rect = document.createElementNS("http://www.w3.org/2000/svg", 'rect')
  rect.setAttribute("width","100%")
  rect.setAttribute("height","100%")
  rect.style.stroke = "#aabbcc"
  rect.style.strokeWidth = "5px"
  rect.style.fill = "#338855"

  const svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
  svg.setAttribute("width","200")
  svg.setAttribute("height","200")
  svg.appendChild(rect)

  const wrapper = document.querySelector(".exampleWrapper")
  wrapper.appendChild(svg)
})

References