Manipulating SVG with JS
Inline SVG is part of the DOM. Use document.getElementById, setAttribute, and event listeners on SVG elements.
Inline SVG is part of the DOM. Use document.getElementById, setAttribute, and event listeners on SVG elements.
<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>
setAttribute is how you modify SVG attributes from JavaScript.