Explain Codes LogoExplain Codes Logo

Creating SVG elements dynamically with JavaScript inside HTML

javascript
svg
event-listeners
accessibility
Anton ShumikhinbyAnton Shumikhin·Feb 4, 2025
TLDR

To generate SVG elements dynamically, such as a rectangle, implement document.createElementNS() alongside the SVG namespace. Here's how:

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); var rect = document.createElementNS(svg.namespaceURI, "rect"); rect.setAttribute("x", "10"); // "x" value. To be replaced with "I am Groot" in the next Avengers movie rect.setAttribute("y", "10"); // "y" coordinate. Y so serious? rect.setAttribute("width", "100"); // width, boldly going where no man has gone before... rect.setAttribute("height", "100"); // ... and height, because why not? rect.setAttribute("fill", "red"); // Paint it, red! svg.appendChild(rect); // Rectangle, you're part of the SVG cool kids group now document.body.appendChild(svg); // Finally, welcome to body. Enjoy the HTML party!

This script synthesizes and attaches a red rectangle to the SVG object within your HTML document.

Avoiding the SVG pitfalls

While designing SVG elements dynamically, you should avoid these common mistakes:

  • The Correct Namespace: SVGs won't render without the correct namespaceURI. Always apply "http://www.w3.org/2000/svg" for SVGs.
  • Attribute Namespaces: Some SVG attributes, such as xlink:href, demand a namespace too. Implement setAttributeNS() where necessary.
  • Accurate Casing: SVGs are case-sensitive, hence SVG attributes like viewBox need to be correctly cased.
  • Event Listeners: To facilitate interactivity, add event listeners to the SVG elements post creation.

Bumping the interactivity up a notch!

Boost user interaction by affixing events to the SVG components:

rect.addEventListener('click', function() { alert('Shouldn\'t you be clicking buttons instead?'); // Click events, because who doesn't like pop-ups? });

Your SVG is now receptive to click events, escalating the scope for enhanced user engagement.

Creating more complex SVG compositions

Assemble an intricate SVG graphic by merging an array of shapes. Group (<g>) your shapes for seamless organization:

// Initiate a group to contain shapes, like Voltron but less robotic let group = document.createElementNS(svg.namespaceURI, 'g'); // More shapes. Because, why stop at one? let circle = document.createElementNS(svg.namespaceURI, 'circle'); circle.setAttribute('cx', '40'); // Still somewhere in the middle of nowhere circle.setAttribute('cy', '40'); // Still center circle.setAttribute('r', '30'); // Radius has a growth spurt group.appendChild(circle); // Circle, meet group. Group, meet circle // Append the group to the SVG element, unite! svg.appendChild(group);

Giving style to SVG attributes

Modify the visual appeal by incorporating style attributes like stroke or fill. Use JavaScript's .style property or .setAttribute() function:

rect.style.stroke = "black"; // Because black goes with everything rect.style.strokeWidth = "2"; // Thin but significant // Or using setAttribute rect.setAttribute("stroke", "black"); // Back in black rect.setAttribute("stroke-width", "2"); // Skinny but mighty

Making SVG elements accessible

While dynamically designing SVGs, consider accessibility. Include relevant attributes like role="img" and aria-labelledby, along with descriptive tags to assist screen reader interpretation.