Select SVG DOM Methods and Objects
The document object model (DOM) is a representation of web documents as connected objects that you can manipulate with JavaScript. SVG documents in web browsers support the core DOM methods defined for all XML and HTML elements.
For the most part, these core methods are the easiest and best-supported way to control the SVG DOM. The main concern is that you use the XML-compatible core DOM methods, and not HTML-specific methods.
However, there are also numerous unique SVG DOM features. This book hasn’t discussed them in depth. But we have highlighted a few particularly useful—and well-supported—DOM features that are unique to SVG.
This appendix collects all the DOM functions and objects we’ve used in the examples into one reference. It is not a complete list of all possible DOM methods for working with SVG.
The list also does not include the basic JavaScript data structures (like objects and arrays), or the HTML DOM methods we used with the HTML form elements in Example 8-X1.
The official references for SVG DOM methods are now scattered between SVG 2, the draft SVG Animation Elements spec, and the Geometry Interfaces Module Level 1 spec. The most up-to-date reference for shared DOM methods is https://dom.spec.whatwg.org/. But in all cases, remember: what is in the spec may not match what is in all browsers that you need to support. Test carefully.
Global Objects and Functions#
These objects are defined as part of the global scope when you run JavaScript in a web document. That means that they are defined as part of the window
object. You can use them directly in your scripts, in the same way that you would use variables that you have declared yourself.
document
#-
A
Document
object that is the root of the DOM tree. See “Document
Properties and Methods” for methods and properties. requestAnimationFrame(callbackFunction)
#-
Asks the browser to callback the screen as soon as practical, and to run the callback function before doing so. The callback function will be passed a timestamp value (in milliseconds) when it is run.
-
callbackFunction
is a JavaScript function object: either an anonymous function or the name of a function declared elsewhere in the script.
-
cancelAnimationFrame(ref)
#-
Cancels an existing animation frame request; the
ref
is the value returned fromrequestAnimationFrame()
. setInterval(callbackFunction, time)
#-
Asks the browser to run the callback function at regular intervals, for as long as the document is open or until the request is cleared.
-
time
is the approximate number of milliseconds between intervals.
-
clearInterval(ref)
#-
Clears (cancels) an existing interval request; the
ref
is the value returned fromsetInterval()
. setTimeout(callbackFunction, time)
#-
Asks the browser to run the callback function after the specified delay.
-
time
is the approximate number of milliseconds until the function is called.
-
clearTimeout(ref)
#-
Clears (cancels) an existing timeout request; the
ref
is the value returned fromsetTimeout()
. encodeURIComponent(string)
#-
Converts a string to a safe format for including in URL query parameters or data URIs.
btoa(data)
#atob(string)
#-
Converts arbitrary binary data (“b”) to base64-encoded format (“a” for ASCII or alphabetical), and vice versa.
Math
#-
A core JavaScript object with properties for mathematical constants and static methods for mathematical functions. These are the ones we used in the examples or supplementary material:
-
Math.PI
for the constant π, used for calculating the geometry of circles and for converting degrees to radians. -
Math.min(...)
andMath.max(...)
for finding the minimum and maximum of a list of values. -
Math.random()
to generate a random number between 0 and 1. -
Math.cos(a)
andMath.sin(a)
for calculating trigonometric ratios from an angle in radians. -
Math.atan2(dy, dx)
for calculating an angle (in radians) from the vertical change (dy
) relative to the horizontal change (dx
). -
There’s also
Math.round(n)
for rounding numbers. However, we instead used aNumber
methodn.toFixed(digits)
, which converts the number to a formatted string, rounded to the specified amount of decimal digits.
-
Date
#-
The JavaScript data type for dates, which also has static functions for parsing dates and accessing the current date. We used
Date.now()
to generate timestamps. performance
#-
An object containing a collection of methods for recording the time it takes your code to execute. The
performance.now()
timestamp is compatible with the timestamps used byrequestAnimationFrame()
(but it doesn’t have as good browser support asDate.now()
). location
#-
An object describing the URL of the current document. We used the
assign()
method to simulate link clicks in Example 18-7. XMLHttpRequest
#-
The class object for requests to the browser to fetch files from the internet for use in this document’s scripts. See “Importing SVG Assets, with AJAX” for more.
Document
Properties and Methods#
The following properties and methods are available on the document
object, for accessing existing elements and creating new ones:
documentElement
#-
-
Gets the root element of the DOM tree for this document.
-
Setting has no effect.
-
createElement(tagName)
#-
-
Returns a new element with that tag name, that is not part of any DOM tree yet.
-
If this is an
HTMLDocument
, the new element will be in the HTML namespace; if the tag name is a recognized HTML tag, the object will be of the correct type to create a fully-functioning HTML element. -
If this is an XML or SVG document, the new element will not have a namespace and will not have any particular behavior or appearance.
-
createElementNS(namespaceURI, tagName)
#-
-
namespaceURI
is the namespace of the attribute as a URL string (not a prefix from the markup). -
Returns a new element with that tag name, in the specified namespace.
-
If the tag name is a recognized tag for that namespace, the object will be of the correct type, with the appropriate behavior and appearance.
-
getElementById(id)
#-
-
Returns the first element in the document with the specified
id
.
-
getElementsByClassName(className)
#-
-
Returns a live list of elements in the document that have the specified class; the list object will be updated as elements are added or removed from the document, or have their class changed.
-
getElementsByTagName(tagName)
#-
-
Returns a live list of elements in the document that have the specified tag name; the list object will be updated as elements are added or removed from the document.
-
There’s also a
getElementsByTagNameNS
method for namespace-specific searches.
-
querySelector(selector)
#-
-
Returns the first element in the document that matches the selector.
-
querySelectorAll(selector)
#-
-
Returns a fixed list of all elements in the document that currently match the selector.
-
Element
Properties and Methods#
The following properties and methods are available on any DOM object representing an element, in all browsers that support SVG:
textContent
#-
-
Gets the concatenated text content of this element and all its children, as a single string.
-
Setting replaces all child text content and elements with the specified string of un-formatted text.
-
namespaceURI
#-
-
Gets the namespace of the current element as a string, which you can use in
createElementNS()
methods. Works regardless of whether this element was created by a parser or by scripts. Will benull
if you usedcreateElement()
in an XML document. -
Setting has no effect.
-
getAttribute(attrName)
#-
-
attrName
is the name of an attribute (without a namespace) on this element. -
Returns the string value of that attribute (or
null
, if there’s no matching attribute).
-
setAttribute(attrName, attrValue)
#-
-
attrName
is the name of the attribute (without a namespace) that you want to create or change. -
attrValue
is any object, which will be converted to a string value using that object’stoString()
method. -
No return value, although invalid values may create errors or warnings.
-
getAttributeNS(namespaceURI, attrName)
#setAttributeNS(namespaceURI, attrName, attrValue)
#-
-
Versions of the attribute functions for XML-namespaced attributes.
-
namespaceURI
is the namespace of the attribute as a URL string (not a prefix from the markup). -
attrName
is the attribute name after removing the prefix and:
separator. -
For example, to access the
xlink:href
attribute value:h
=
element
.
getAttributeNS
(
"http://www.w3.org/1999/xlink"
,
"href"
);
-
Returns values are the same as the un-namespaced versions.
-
appendChild(node)
#-
-
Adds the specified
Node
object (an element or a text node object) as the last child of the current element; if necessary, it removes the node from whatever DOM tree it is currently a child of.
-
insertBefore(node, sibling)
#-
-
Adds the specified
Node
object as a child . -
For example, to add a newly-created
<title>
element to a<g>
as the first child of that group, you’d need to insert it before the current first child element:group
.
insertBefore
(
title
,
group
.
firstChild
);
-
If
sibling
isnull
, this is the same asappendChild(node)
. -
If
sibling
isn’t a direct child of this element, creates an error.
-
addEventListener(eventName, listenerFunction, options)
#-
-
eventName
is a string describing the event, like “click” or “keypress”. -
listenerFunction
is a JavaScript function object: either an anonymous function or the name of a function declared elsewhere in the script. When the event happens, the function will be run with theEvent
object as a parameter. -
options
modify when and how the listener function is triggered; consult a DOM scripting reference for more. -
No return value.
-
removeEventListener(eventName, listenerFunction, options)
#-
-
Cancels an event listener.
-
eventName
,listenerFunction
, andoptions
must exactly match the values used inaddEventListener()
. -
No return value.
-
cloneNode(deepCloneFlag)
#-
-
Returns an independent clone of the current element; unlike
<use>
clones, this clone can be modified independently from the original. -
deepCloneFlag
is a boolean value (something that equals eithertrue
orfalse
); if true, the text content and child elements of this element will be cloned as well.
-
The following properties and methods are not part of the core DOM Element
interface, but should be available on both SVG and HTML elements. However, except for style
, browser support on SVG elements is not as good as for HTML elements, so remember to test carefully:
style
#-
An object representing all inline styles set on this element. Modifying it is equivalent to modifying the
style
attribute.-
The easiest way to read and modify styles is to use JavaScript object notation, with the property name as the object key. CSS properties with hyphens (
-
) in the name can be optionally accessed in camelCase format (hyphens removed, letters after a hyphen capitalized). This allows you to use dot notation (.propertyName
) instead of array notation (["property-name"]
).For example, the following would create a dashed stroke with dashes and gaps equal to the
stroke-width
:path
.
style
[
"stroke-dasharray"
]
=
path
.
style
.
strokeWidth
;
-
setProperty(propertyName, newValue, important)
can also be used to set properties; it is currently required for setting CSS variables. Ifimportant
is used, it must be either an empty string (""
) or the literal string"important"
. If you provide anewValue
that the CSS parser does not consider valid for this property, the method has no effect. -
getPropertyValue(propertyName)
returns the value of the style property, if it is set. -
getPropertyPriority(propertyName)
returns"important"
or""
. -
removeProperty(propertyName)
removes the style declaration.
-
classList
#-
An object representing the set of class names on this element, as a list. Modifying it is equivalent to modifying the
class
attribute.-
add(className)
adds the specified class if it isn’t already in the list. -
remove(className)
removes the class if it is in the list. -
contains(className)
returnstrue
orfalse
depending on whether the class is in the list. -
toggle(className)
removes the class if it is already in the list, or adds it otherwise, and returnstrue
orfalse
depending on whether the list contains the class after the toggle is complete.
-
innerHTML
#-
-
Gets all the child elements and text content of this element as a single markup string.
-
Setting replaces all the child content of this element with the result of parsing the (markup string) value you set it to; the type of parser (HTML or XML) depends on the type of the current document.
-
focus()
#-
Gives this element keyboard focus, if it is focusable.
blur()
#-
Removes keyboard focus from this element if it has it (usually switching it to the document window or body). Not recommended; instead, apply
focus()
to a specific other element.
DOM Events#
Event listener functions are called with an Event
object as a parameter. Some properties of the object are shared by all events, others are specific to the event type:
target
#-
The object (usually an element) that initially received the event. For example, the most specific element that a user clicked, or the element that had keyboard focus when a keyboard event was made.
currentTarget
#-
The object to which the listener function was attached. It could be the
target
, or it could be an ancestor in the DOM tree. preventDefault()
#-
Marks this event as having already been handled, so that the browser does not react to it as well.
clientX
andclientY
#-
On mouse and touch events, describe the location of the event, measured in
px
units relative to the browser window. This is the coordinate system used as the reference forgetScreenCTM()
method on SVG elements. charCode
#-
On keyboard events, represents the key that was pressed as an integer value. Non-standard, but well-supported. The newer, standard
key
property will replace it eventually.
Shared SVG DOM Element Properties and Methods#
Any element in the SVG namespace inherits from the class SVGElement
, and therefore shares some common properties and methods.
In addition, there are shared subclasses specifically for elements with visual representation on the screen, and for shapes in particular. The exact structure of classes and inheritance has changed from SVG 1 to SVG 2, but the following methods should be available on shapes, <text>
, <foreignObject>
, <image>
, <g>
, <a>
, and <svg>
:
getBBox()
#-
Calculates the object bounding box of this element, in its own coordinate system.
-
Returns an
SVGRect
(SVG 1) orDOMRect
(SVG 2) object. -
SVG 2 adds an
options
parameter that can change how the bounding box is calculated.
-
getScreenCTM()
#-
Calculates the cumulative transformation matrix for this element, relative to the browser’s base coordinate system.
-
Returns an
SVGMatrix
(SVG 1) orDOMMatrix
(SVG 2) object, representing the transformation required to convert points in this element’s coordinate system into measurements relative to the browser window rectangle and the default browser zoom scale (which is known elsewhere in the DOM as the “client” coordinate system).
-
Path-related Methods#
The following methods were defined in SVG 1 to only apply to <path>
elements. In SVG 2 (and some of the latest browsers), they are available for all shapes.
getTotalLength()
#-
Calculates the length of the path (stroking distance), combining together all subpaths and skipping all move-to discontinuities. Not affected by the
pathLength
attribute.-
Returns a number, representing the length in SVG user units (scaled
px
units). -
Length calculations may be slightly different from one browser to the next.
-
getPointAtLength(distance)
#-
Locates a point on the path that is the specified distance from the start of the path, using the same measurement rules as
getTotalLength()
and the same start point as stroke dashing. Not affected by thepathLength
attribute.-
distance
is a number representing a length in SVG user units (scaledpx
units); the browser will clamp the value you provide to the range from 0 to the total length of the path. -
Returns an
SVGPoint
(SVG 1) orDOMPoint
(SVG 2) object, withx
andy
set to the coordinates of the point.
-
Text-related Methods#
SVG text elements (<text>
, <tspan>
, and <textPath>
) have a number of methods for measuring text, as described in “Measuring the Message” in Chapter 7. This reference includes a few methods we couldn’t fit into that section.
All the character-counting methods use UTF-16 blocks, the same as the basic JavaScript string methods. If multiple characters are represented by the same visual glyph (letter-shape), then they will return the same geometry data. See “Geometry Objects and Methods” for details on the geometry objects returned; SVG 1 and older browsers use the SVG*
names, SVG 2 and some new browsers use DOM*
names.
getComputedTextLength()
#-
Calculates the total offset length of the text for this element in the inline (writing mode) direction, including letter and word spacing and
dx
ordy
offsets, but not including absolute changes in position. Not affected bytextLength
.-
Returns a number representing the length in SVG user units (scaled
px
units).
-
getSubStringLength(charIndex, numChars)
#-
Calculates the total offset length for a substring of the text.
-
charIndex
is an integer for the index of the first character; also equal to the number of characters to skip before the start. -
numChars
is the (integer) number of characters to include. -
Returns a number representing the length in SVG user units (scaled
px
units).
-
getStartPositionOfChar(charIndex)
#-
Calculates the text layout position before positioning this character. For left-to-right text, this will be the intersection of the baseline with the left edge of the character.
-
Returns an
SVGPoint
orDOMPoint
object.
-
getEndPositionOfChar(charIndex)
#-
Calculates the text layout position after positioning this character. For left-to-right text, this will be the intersection of the baseline with the right edge of the character.
-
Returns an
SVGPoint
orDOMPoint
object.
-
getExtentOfChar(charIndex)
#-
Calculates a bounding box for this character. The box is the tightest rectangle that will fit around the (possibly rotated) glyph layout box. It is not based on the actual glyph shape.
-
Returns an
SVGRect
orDOMRect
object.
-
getRotationOfChar(charIndex)
#-
Calculates the rotation angle for this character, whether set by
rotate
or by<textPath>
.-
Returns a number for the angle in degrees.
-
getCharNumAtPosition(point)
#-
Identifies which character would be underneath a particular point within the text element, using the “top” character layer for overlapping letters.
-
point
is anSVGPoint
orDOMPoint
object, such as could be generated from a mouse event and thegetScreenCTM()
for this element. -
Returns an integer for the index of the character within the string, or -1 if the point isn’t in any glyph layout boxes.
-
SVG/SMIL Animation Methods#
The SVGSVGElement
has methods for controlling the SVG/SMIL animation timeline in a coordinated way. These methods only affect SVG/SMIL animations, not CSS animations or requestAnimationFrame()
:
getCurrentTime()
#-
Returns the time relative to the animation timeline, as a number of seconds (with decimals). If you haven’t used the other methods, this will be the time since the document’s load event.
setCurrentTime(time)
#-
Changes the time on the animation timeline, causing all animations to advance or rewind in sync.
-
time
is a number representing a time in seconds
-
pauseAnimations()
#-
Pauses all animations; the current time on the animation timeline does not change while animations are paused.
unPauseAnimations()
#-
Restarts paused animations, allowing the current time to move forward as normal.
Individual animation elements (<animate>
, <set>
, <animateTransform>
, and <animateMotion>
) have a variety of properties and methods, of which the most useful are:
targetElement
#-
-
Gets the element which this animation will affect, regardless of whether that is the parent element or an element defined by an
xlink:href
cross-reference. -
Read-only
-
beginElement()
#-
Creates a new begin trigger for this element, starting it unless prevented by
restart="never"
attribute. endElement()
#-
Creates a new end trigger for this element, ending any active animation (possibly with a delay caused by a
min
attribute). beginElementAt(delay)
#endElementAt(delay)
#-
Sets a begin or end trigger for this element, to apply after a certain delay
-
delay
is a number representing a time in seconds
-
Geometry Objects and Methods#
The SVG DOM defined three geometry-related data objects, which have now been extended and replaced (in the Geometry Interfaces Module Level 1 spec) by generic DOM geometry objects.
SVGRect
orDOMRect
#-
A geometric rectangle, used as the result of
getBBox()
andgetExtentOfChar()
. Not a<rect>
element.-
x
,y
,width
,height
are numbers representing the position and size of the rectangle, in SVG user units (scaledpx
units) for the current coordinate system.
-
SVGPoint
orDOMPoint
#-
A geometric (x,y) point. For
DOMPoint
, can also be used for a point in 3D space.-
x
andy
are numbers representing the position of the point, in SVG user units (scaledpx
units) for the current coordinate system. -
matrixTransform(matrix)
returns a new point object which is the result of transforming the current point by the specified matrix.
-
SVGMatrix
orDOMMatrix
#-
A transformation matrix. For
SVGMatrix
, this is a 2D transformation matrix. ForDOMMatrix
, it can represent either a 2D or 3D transformation. Various methods allow you to do transformation-related matrix math. We only used one:-
inverse()
returns a new matrix object that has the reverse effect as this one.
-
The new (DOM*
) versions of these objects have constructor forms, so you can create new objects with the new
JavaScript keyword. However, for best compatibility, create them with the utility methods available on every <svg>
element:
createSVGPoint()
#-
Returns a new
SVGPoint
orDOMPoint
object, initialized to the point (0,0). createSVGMatrix()
#-
Returns a new
SVGMatrix
orDOMMatrix
object, initialized to an identity matrix (that is, a matrix representing a transformation that doesn’t change anything).
Other SVG DOM Objects#
In SVG 1, the cloned versions of SVG graphics within a <use>
element shadow tree are SVGElementInstance
objects. Their most important property is correspondingUseElement
, which references the <use>
element in the main document tree.