SVG with JavaScript
SVG (Scalable Vector Graphics) describes pictures as shapes in markup: <rect>, <circle>, <path>, <text>. Unlike canvas pixels, SVG shapes are real DOM elements: you can select them, change their attributes, style them with CSS, attach click listeners and give them accessible names. And because they're vectors, they stay sharp at any size. That makes SVG ideal for icons, diagrams and charts with a moderate number of elements.
In One Minute
- SVG elements live in the DOM like HTML elements, so
querySelector,setAttribute,classListand events all work. - Create them with
document.createElementNS("http://www.w3.org/2000/svg", "rect"), notcreateElement. - Set geometry with attributes (
x,y,width,height,cx,r,d) viasetAttribute. - The
viewBoxattribute defines an internal coordinate system that scales to any size. - Make SVG accessible with
role="img", a<title>, andaria-labels, or a data table alternative.
SVG in the Page
An <svg> element written in HTML is part of the DOM right away:
<svg id="pic" width="200" height="100" viewBox="0 0 200 100">
<rect id="bar" x="10" y="40" width="80" height="50" fill="seagreen" />
<circle cx="150" cy="50" r="30" fill="orange" />
<text x="10" y="25" font-size="14">Fee Tracker</text>
</svg>
<script>
const bar = document.querySelector("#bar");
console.log(bar.tagName, bar.getAttribute("width"));
bar.setAttribute("width", "120");
bar.setAttribute("fill", "royalblue");
console.log(bar.getAttribute("width"), bar.getAttribute("fill"));
console.log(document.querySelectorAll("#pic circle, #pic rect").length);
</script>rect 80
120 royalblue
2Note tagName is lowercase (rect) for SVG elements, unlike HTML's uppercase. Changing an attribute redraws the shape immediately.
Creating SVG Elements
SVG elements belong to a different namespace than HTML. document.createElement("rect") creates an unknown HTML element that draws nothing. Use createElementNS with the SVG namespace:
<svg id="pic" width="200" height="100"></svg>
<script>
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("#pic");
const wrong = document.createElement("rect");
const right = document.createElementNS(SVG_NS, "rect");
console.log(wrong instanceof SVGElement, right instanceof SVGElement);
for (const [attr, value] of Object.entries({ x: 20, y: 20, width: 100, height: 40, fill: "seagreen" })) {
right.setAttribute(attr, value);
}
svg.append(right);
console.log(Math.round(right.getBBox().width), svg.children.length);
</script>false true
100 1getBBox() measures a shape's bounding box in SVG coordinates, which only works for real SVG elements in the document. A small helper makes creation pleasant:
const SVG_NS = "http://www.w3.org/2000/svg";
function svgEl(tag, attrs = {}) {
const el = document.createElementNS(SVG_NS, tag);
for (const [name, value] of Object.entries(attrs)) el.setAttribute(name, value);
return el;
}Common Shapes
| Element | Key attributes |
|---|---|
<rect> | x, y, width, height, rx (rounded corners) |
<circle> | cx, cy, r |
<ellipse> | cx, cy, rx, ry |
<line> | x1, y1, x2, y2 |
<polyline> / <polygon> | points="10,10 50,30 90,10" |
<path> | d (a mini-language: M move, L line, C curve, A arc, Z close) |
<text> | x, y, text-anchor, font-size; the text goes inside (textContent) |
<g> | Groups shapes; a transform on it moves them all |
Shared presentation attributes: fill, stroke, stroke-width, opacity, transform. Most can also be set in CSS.
viewBox: Scaling Without Blur
The viewBox attribute ("minX minY width height") defines the coordinate system you draw in. The browser scales it to whatever size the SVG is displayed at:
<svg id="small" width="100" height="50" viewBox="0 0 200 100"><rect x="0" y="0" width="200" height="100" fill="gold" /></svg>
<svg id="large" width="400" height="200" viewBox="0 0 200 100"><rect x="0" y="0" width="200" height="100" fill="gold" /></svg>
<script>
for (const id of ["small", "large"]) {
const rect = document.querySelector(`#${id} rect`).getBoundingClientRect();
console.log(id, rect.width, "x", rect.height);
}
</script>small 100 x 50
large 400 x 200The same drawing (200 by 100 units) rendered at two sizes, perfectly sharp at both. For responsive charts, set a viewBox, then size the <svg> with CSS (width: 100%; height: auto), and it fills its container.
Styling and Events
Shapes are DOM elements, so CSS classes and event listeners work exactly as with HTML:
<style>.bar { fill: seagreen; } .bar.selected { fill: royalblue; }</style>
<svg id="chart" width="200" height="100">
<rect id="g9" class="bar" data-grade="9" x="10" y="30" width="40" height="60" />
<rect id="g11" class="bar" data-grade="11" x="70" y="50" width="40" height="40" />
</svg>
<script>
document.querySelector("#chart").addEventListener("click", (event) => {
const bar = event.target.closest(".bar");
if (!bar) return;
bar.classList.toggle("selected");
console.log(`grade ${bar.dataset.grade} selected: ${bar.classList.contains("selected")}`);
console.log("fill now:", getComputedStyle(bar).fill);
});
</script>grade 9 selected: true
fill now: rgb(65, 105, 225)Event delegation, dataset, classList and closest all work on SVG. Hover effects can be pure CSS (.bar:hover { opacity: 0.8; }).
Accessible SVG
| Technique | When |
|---|---|
role="img" plus aria-label (or a <title> as the first child) on the <svg> | The graphic is one picture with one description |
aria-hidden="true" | The SVG is decorative, or repeats nearby text |
| A visible data table or list beside it | Charts with several values |
<title> inside individual shapes | Native tooltips, and names for interactive shapes |
tabindex="0" and keyboard handlers | Interactive shapes that keyboard users must reach |
SVG or Canvas?
| SVG | Canvas | |
|---|---|---|
| Model | Shapes are DOM elements | Pixels, redrawn by code |
| Scaling | Sharp at any size | Must be resized and redrawn |
| Events and CSS on parts | Yes, per shape | No, compute hits yourself |
| Accessibility | Can label shapes | Only a fallback for the whole canvas |
| Many objects (10,000+) | Slows down (DOM cost) | Fast |
| Best for | Icons, diagrams, charts, maps with moderate detail | Games, image editing, dense data, effects |
In Practice
The Fee Tracker's responsive, accessible bar chart in SVG, built from data with a helper, with a viewBox for scaling and a title for screen readers:
<div id="chart-box" style="width: 100%"></div>
<script>
const SVG_NS = "http://www.w3.org/2000/svg";
const svgEl = (tag, attrs = {}) => {
const el = document.createElementNS(SVG_NS, tag);
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
return el;
};
function barChart(data, { width = 300, height = 160 } = {}) {
const max = Math.max(...data.map((d) => d.total));
const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", style: "width: 100%; height: auto" });
const title = svgEl("title");
title.textContent = "Totals by grade: " + data.map((d) => `${d.label} $${d.total}`).join(", ");
svg.append(title);
const slot = width / data.length;
data.forEach((d, i) => {
const h = (d.total / max) * (height - 40);
const x = i * slot + slot * 0.2;
svg.append(svgEl("rect", { x, y: height - 20 - h, width: slot * 0.6, height: h, fill: "seagreen" }));
const label = svgEl("text", { x: x + slot * 0.3, y: height - 5, "text-anchor": "middle", "font-size": 12 });
label.textContent = d.label;
svg.append(label);
});
return svg;
}
const chart = barChart([{ label: "Grade 9", total: 165 }, { label: "Grade 11", total: 85 }, { label: "Grade 12", total: 300 }]);
document.querySelector("#chart-box").append(chart);
console.log(chart.querySelectorAll("rect").length, "bars");
console.log(chart.querySelector("title").textContent);
</script>3 bars
Totals by grade: Grade 9 $165, Grade 11 $85, Grade 12 $300Labels are set with textContent, so even grade labels from user data are safe.
Common Mistakes
Using createElement for SVG. The element is in the HTML namespace and draws nothing. Use createElementNS.
Assigning geometry as properties. rect.width = 100 doesn't work (rect.width is an animated-length object). Use setAttribute("width", 100).
Forgetting viewBox. The drawing won't scale with its container.
Building SVG from strings with user data. SVG can contain scripts and event attributes; the same XSS rules as HTML apply. Use createElementNS and textContent.
Practice
Challenge: Using createElementNS, add three circles to an SVG at x = 30, 80 and 130 (y = 50, radius 20), and log how many circles the SVG contains.
Show solution
<svg id="s" width="160" height="100"></svg>
<script>
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("#s");
for (const cx of [30, 80, 130]) {
const c = document.createElementNS(SVG_NS, "circle");
c.setAttribute("cx", cx);
c.setAttribute("cy", 50);
c.setAttribute("r", 20);
svg.append(c);
}
console.log(svg.querySelectorAll("circle").length);
</script>3Key Takeaways
| Task | Code |
|---|---|
| Create a shape | document.createElementNS(SVG_NS, "circle") |
| Set geometry | el.setAttribute("r", 20) |
| Scale to container | viewBox="0 0 300 160" + CSS width: 100% |
| Measure a shape | el.getBBox() |
| Name the graphic | role="img" + <title> |
Was this tutorial helpful?