How to Manipulate SVG Elements Using JavaScript DOM
Scalable Vector Graphics (SVG) are XML-based vector images integrated directly into the browser’s Document Object Model (DOM). Because inline SVG elements exist as standard DOM nodes, JavaScript can access, create, modify, style, and animate vector graphics in real time. Through standard DOM methods and specialized SVG DOM interfaces, developers can transform static graphics into interactive user interface components, dynamic data visualizations, and reactive animations.
Direct DOM Access and Selection
Because inline <svg> elements are part of the
active web document, you can target individual shapes—such as
<path>, <circle>,
<rect>, and <g> (groups)—using
familiar DOM selection methods:
const circle = document.getElementById('status-indicator');
const paths = document.querySelectorAll('svg.chart path');Once selected, these nodes can be read or modified just like standard HTML elements.
Creating Elements with XML Namespaces
Unlike standard HTML elements, SVG elements belong to the W3C SVG
namespace (http://www.w3.org/2000/svg). To dynamically
generate SVG elements in JavaScript, you must use
document.createElementNS() rather than
document.createElement():
const svgNS = "http://www.w3.org/2000/svg";
const newRect = document.createElementNS(svgNS, "rect");
newRect.setAttribute("x", "10");
newRect.setAttribute("y", "10");
newRect.setAttribute("width", "100");
newRect.setAttribute("height", "50");
newRect.setAttribute("fill", "#007acc");
document.getElementById('my-svg').appendChild(newRect);Failing to declare the correct namespace will result in elements
being created as generic HTMLUnknownElement instances,
preventing them from rendering.
Modifying Attributes and Inline Styles
SVG appearance and layout are defined primarily through XML attributes and CSS properties. You can modify these properties dynamically:
- Attribute Manipulation: Use
setAttribute()to modify geometry attributes such ascx,cy,r,d, ortransform. - Style Properties: Modify presentation attributes
using the standard
styleproperty (e.g.,element.style.fill = 'red'orelement.style.strokeWidth = '2px'). - Class Management: Use
element.classList.add(),remove(), ortoggle()to apply external CSS rules dynamically.
Event Handling on Individual Shapes
Every shape inside an SVG can listen for user interactions. You can attach event listeners directly to specific vector paths or groups:
const interactivePath = document.querySelector('#map-region');
interactivePath.addEventListener('click', (event) => {
event.target.setAttribute('fill', '#ff5722');
});This allows granular interactivity, such as tooltips on chart data points or hover states on interactive maps, without relying on canvas hit-detection algorithms.
Specialized SVG DOM Interfaces
The SVG DOM provides specialized interfaces tailored to vector geometry:
- Path Calculations (
SVGPathElement): Methods likegetTotalLength()andgetPointAtLength(distance)allow developers to calculate path dimensions for complex stroke-dash animations or along-path motion. - Coordinate Transformations
(
SVGGraphicsElement): Methods likegetBBox()return the bounding box of an element, whilegetScreenCTM()provides transformation matrices to convert screen coordinates to SVG coordinate space. - Point Manipulation: Using
svg.createSVGPoint()combined with matrix multiplication enables accurate mapping of mouse or touch events to internal SVG coordinates.