MDN self-hosted library · e01.org

Scripting SVG with JavaScript

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<svg
  viewBox="0 0 100 100"
  width="100"
  height="100"
  xmlns="http://www.w3.org/2000/svg">
  <circle id="dot" cx="50" cy="50" r="40" fill="steelblue" />
  <script>
    let colorIndex = 0;
    document.getElementById("dot").addEventListener("click", (event) => {
      colorIndex = (colorIndex + 1) % 2;
      event.target.setAttribute(
        "fill",
        ["steelblue", "lightskyblue"][colorIndex],
      );
    });
  </script>
</svg>
html
<svg
  viewBox="0 0 100 100"
  width="100"
  height="100"
  xmlns="http://www.w3.org/2000/svg"></svg>
js
const svgNS = "http://www.w3.org/2000/svg";
const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute("cx", 50);
circle.setAttribute("cy", 50);
circle.setAttribute("r", 40);
circle.setAttribute("fill", "steelblue");
document.querySelector("svg").append(circle);
html
<svg
  id="grid"
  viewBox="0 0 100 50"
  width="400"
  height="200"
  xmlns="http://www.w3.org/2000/svg">
  <rect width="100" height="50" fill="whitesmoke" />
  <circle id="marker" cx="-10" cy="-10" r="3" fill="crimson" />
</svg>
<output id="readout">Move the pointer over the graphic.</output>