13.4 Scripting SVG - Nodes, attributes, styles

DOM Nodes

As the SVG viewer reads the markup (structure) in an SVG document, it creates a tree of nodes, which are objects in memory that correspond to the structure and content of the markup. This is the Document Object Model (DOM), and it is accessible to your scripts.

The first thing you need to do in order to deal with the DOM is to access the nodes.

DOM Nodes' Attributes

Once you have an element's node, you can reach and modify its attributes and styles. You can:

DOM Nodes' Styles

You could modify inline styles using element.setAttribute("style",newStyleValue), but this overwrites all styles on the element.
Instead, you can work with the element.style property. Use: If you do want to set all styles at once, then you can directly modify element.style.cssText, which is a string representation of all the styles in property-name: value format. When you read this property, it returns the concatenated text of all of the node's descendants. If you set it, you will replace any descendant nodes with a single text block.

Example. Script that displays info about the rectangle and changes its property

Notice. The script in Example 13-5 is included in the SVG file after the <rect> and <text> elements that it uses. This ensures that the elements exist in the DOM before the script is run.

Accessing Content in SVG

Explanation

  1. In order to easily access an element from a script, give it a unique id.
  2. The <![CDATA[ is used to ensure that any stray < or > signs
    are not interpreted as markup.
  3. Select elements from the document by id, and save the results in variables:
    var txt = document.getElementById("output");
    var r = document.getElementById("rectangle");
  4. The results of getAttribute() and style.getPropertyValue() are strings; these are concatenated together with + to create the message string.
  5. This r.setAttribute("height", "30"); changes the height of the rectangle to convert it to a square.
  6. Finally txt.textContent= msg;, set the content of the <text> element to display the attributes.
<svg width="300" height="100" viewBox="0 0 300 100"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Accessing Content in SVG</title>
<rect id="rectangle" x="10" y="20" width="30" height="40"
style="stroke:gray; fill: #ff9; stroke-width:3"/>
<text id="output" x="10" y="80" style="font-size:9pt"></text>
<script type="application/ecmascript">
    // <![CDATA[
    var txt = document.getElementById("output");
    var r = document.getElementById("rectangle");
    var msg = r.getAttribute("x") + ", " +
    r.getAttribute("y") + " " +
    r.style.getPropertyValue("stroke") + " " +
    r.style.getPropertyValue("fill");
    r.setAttribute("height", "30");
    txt.textContent= msg;
    // ]]>
</script>
</svg>