Chapter 14. Using the SVG DOM

The methods and properties used in the scripting examples in Chapter 13—creating and selecting elements, getting and setting styles and attributes—are part of the Document Object Model (DOM) specification, and are not unique to SVG. The SVG 1.1 specifications define numerous additional methods to make it easier to work with the two-dimensional graphical layout of SVG. These methods allow you to figure out exactly where your text or path elements have been drawn, control the timing of your animation elements, and convert between transformed coordinate systems.

Determining the Value of Element Attributes

In Scripting SVG, we used getAttribute and setAttribute to access element attributes. Those methods treat the attributes as simple strings, without worrying about what they represent. If you need to calculate the difference in width between an element with width="10em" and an element with width="100px", you would need to extract the numbers from the strings, find out the font size, and convert the measurements.

To make things easier, SVG element objects have properties representing the key attributes for that element type. An SVGCircleElement object, which represents a <circle> in your SVG code, has properties cx, cy, and r. An SVGRectElement (a <rect> in markup) has properties x, y, width, and height.

These properties don’t store simple numbers, however. In most cases, the properties each contain two subproperties: baseVal and animVal. The animVal object ...

Get SVG Essentials, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.