How do I create an SVG element with JavaScript? I tried this:
var svg = document.createElement('SVG'); svg.setAttribute('style', 'border: 1px solid black'); svg.setAttribute('width', '600'); svg.setAttribute('height', '250'); svg.setAttribute('version', '1.1'); svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); document.body.appendChild(svg);
However it creates an SVG element with zero width and zero height.
For an external SVG, you can use the same code when adding the <script> element into the SVG itself. However, you may want to wrap the code with CDATA. If you don't, then the XML parse will consider the JS code part of XML, and if you use < or >, it will break (as in this example), thinking you're trying to start or end a tag.
Definition and Usage The <svg> tag defines a container for SVG graphics. SVG has several methods for drawing paths, boxes, circles, text, and graphic images. To learn more about SVG, please read our SVG Tutorial.
All of the following demos have an empty SVG element in the HTML. I’ve manually added it, but you can create and add it via JavaScript as well. I also used a background rectangle so we can see what we’re doing.
You can dynamically create curves and paths too, but that’s a bit more involved so I’ll save it for another tutorial. I hope you picked up a few pixels of information about creating dynamic SVG elements. Until next time, keep your pixels movin’.
You forgot the Namespace URI of your svg
element and xmlns
attribute.
Also, version
is ignored by all browsers.
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute('style', 'border: 1px solid black'); svg.setAttribute('width', '600'); svg.setAttribute('height', '250'); svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); document.body.appendChild(svg);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With