SyntaxStudy
Sign Up
HTML SVG and JavaScript DOM
HTML Intermediate 4 min read

SVG and JavaScript DOM

Manipulating SVG with JS

Inline SVG is part of the DOM. Use document.getElementById, setAttribute, and event listeners on SVG elements.

Example
<svg id="chart" width="300" height="80" xmlns="http://www.w3.org/2000/svg">
  <rect id="bar" x="0" y="10" width="0" height="60" fill="steelblue"/>
</svg>
<button onclick="animateBar()">Animate</button>
<script>
function animateBar() {
  let w = 0;
  const bar = document.getElementById("bar");
  const id = setInterval(() => {
    w += 3;
    bar.setAttribute("width", w);
    if (w >= 280) clearInterval(id);
  }, 10);
}
</script>
Pro Tip

setAttribute is how you modify SVG attributes from JavaScript.