JavaScript in SVG (Create, Edit, Destroy Elements)
In the previous section, we looked at the mechanics of executing JavaScript. Now, let's look at how to create and destroy elements within a SVG document.
Creating Elements
Programmatically creating SVG elements is fairly straight forward. The element node is created. All the element's attributes are individually set. The element node is then added to the document as a child of an existing element node.
// Place the SVG namespace in a variable to easily reference it. var xmlns = "http://www.w3.org/2000/svg"; var elem = document.createElementNS(xmlns, "rect"); elem.setAttributeNS(null,"x",50); elem.setAttributeNS(null,"y",50); elem.setAttributeNS(null,"width",50); elem.setAttributeNS(null,"height",50); elem.setAttributeNS(null,"fill", "blue"); document.documentElement.appendChild(elem);
Creating Text
Text has the added complication that the text displayed by the text element is a child node. So, it also needs to explicitly created and then appended as a child of the text element node.
// Place the SVG namespace in a variable to easily reference it. var xmlns = "http://www.w3.org/2000/svg"; var txtElem = document.createElementNS(xmlns, "text"); txtElem.setAttributeNS(null,"x",50); txtElem.setAttributeNS(null,"y",50); txtElem.setAttributeNS(null,"font-size",15); var helloTxt = document.createTextNode("Hello World!"); txtElem.appendChild(helloTxt) document.documentElement.appendChild(txtElem);
Editing Attributes
Editing attributes is quite easy as well. You just get the node object and use setAttributeNS(...). Attributes that are in a different namespace like 'xlink:href' will not show up if you just pass in null as the namespace.
<rect id="myRectangle" width="10" height="10" fill="blue" /> <image id="myImage" y="20" width="300" height="300" xlink:href="dog.jpg" />
var rectNode = document.getElementById("myRectangle"); var imgNode = document.getElementById("myImage"); var xlinkns = "http://www.w3.org/1999/xlink"; // Will turn the rectangle green rectNode.setAttributeNS(null, "fill", "green"); // Will switch to a different image. Requires namespace to be set. imgNode.setAttributeNS(xlinkns, "xlink:href", "cat.jpg");
Destroying Nodes
Removing nodes is done by calling removeChild(...) from the parent node.
document.documentElement.removeChild(txtElem);
The act of removing nodes alters the childNodes array so if you're trying to remove all the nodes from a parent then code carefully.
Example
The following example creates 'use' elements that have a random fill and stroke. It then gradually fades the opacity and then finally removes elements that can no longer be seen.