Changing SVG styles with the DOM API
15 November 2016

SVGs are great. Not only do they render non-pixelated versions of your favorite vector images, but their XML base allows developers so much freedom to play with them. It’s also a good exploration of what can be done with the DOM API.

Accessing the SVG

It turns out that the DOM API can be used not only for HTML, but XML and SVG as well. SVGs can then be accessed by any DOM API method you choose. The simplest and most common one is through the getElementById method.

1
let svg = document.getElementById("my_svg");

SVGs inside object tags or iframes need an additional step. After getting the object or iframe element, you'll need to use contentDocument to access its SVG content.

1
2
3
let obj = document.getElementById("objectsvg");
let svgdoc = obj.contentDocument;
let svg = svgdoc.getElementById("my_svg");

Note that if an SVG is displayed using an img tag, the following steps won't work. img tags render the SVGs as just that, images. Thus, their DOM elements can no longer be accessed programmatically.

Accessing child elements

Elements within the SVG are inside the children attribute. It is in the form of an HTMLCollection though. Since HTMLCollections aren't iterators they can't be looped through using a forEach. It needs to be iterated using the classic, for (let i = 0; i < svg.children.length; i++)

Changing style

SVG element styles can easily be changed. Each element has a classList, as its name implies, it's a collection of an element's classes. This attribute is read-only though and can only be manipulated through its add and remove methods. Below is a sample of iterating through elements in an SVG, changing all of one class into another.

1
2
3
4
5
6
7
for (let i = 0; i < svg.children.length; i++) {
    let child = svg.children[i];
    if (child.classList.contains("oldstyle")) {
        child.classList.remove("oldstyle");
        child.classList.add("newstyle");
    }
}