Skip to content

Lesson 1 of 9 · 24m

SVG Is a DOM: Manipulate Structure, Not Pixels

Learn the retained-mode mental model for SVG, when direct DOM edits beat redraws, and how namespaces, transforms, and event delegation really work.

The first slow network diagram I reviewed rebuilt an entire SVG string on every mouse move. The browser was not slow because SVG was slow; the application treated a retained-mode scene graph like a bitmap. SVG keeps nodes alive. You change the nodes that changed, and the browser owns invalidation and painting.

SVG nodes are real DOM nodes

A circle remains a circle after rendering. It can receive events, expose semantics, and be updated independently:

<svg viewBox="0 0 240 120" role="img" aria-labelledby="chart-title">
  <title id="chart-title">Deploy frequency by service</title>
  <circle id="api" cx="40" cy="60" r="18" fill="#4f7cff"></circle>
  <circle id="worker" cx="120" cy="60" r="30" fill="#49b883"></circle>
</svg>
const worker = document.querySelector('#worker')
worker.setAttribute('r', 34)
worker.classList.add('is-hot')

There is no redraw call. Mutating the attribute dirties the affected rendering state.

Namespaces matter outside inline HTML

document.createElement('circle') creates an unknown HTML element, not an SVG circle:

const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle')
circle.setAttribute('r', '12')
svg.appendChild(circle)

If dynamically created SVG silently does not render, check the namespace before checking geometry.

Use structure for transforms and events

<g id="viewport" transform="translate(24 10) scale(1.35)">
  <g class="service" transform="translate(120 80)"><rect width="60" height="36"/></g>
</g>
svg.addEventListener('click', event => {
  const node = event.target.closest('[data-service]')
  if (node && svg.contains(node)) selectService(node.dataset.service)
})

Parent transforms affect children in a predictable local coordinate space. One delegated listener survives large graphs better than thousands of per-node listeners. For stateful presentation, toggle classes and let CSS own the visual treatment instead of rewriting a dozen attributes per node.

Field notes

  • innerHTML is fine for initial hydration but destructive during interaction: it drops node identity, focus, listeners, and transitions.
  • SVG loaded through <img> is inert to the parent document; use inline SVG when you need scripting or events.
  • getBBox() forces layout and is expensive inside dense loops. Cache measurements.
  • When thousands of independently moving primitives make the DOM itself the bottleneck, move that layer to canvas.

Was this lesson helpful?

Sign in to rate