Ran into a problem today with attempting to manipulate textPath
SVG elements within the DOM. Consider the following, where the variable svg
is an SVG element in your DOM:
var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
var label_container = document.createElementNS("http://www.w3.org/2000/svg", "text");
var label = document.createElementNS("http://www.w3.org/2000/svg", "textPath");
label.setAttributeNS("http://www.w3.org/1999/xlink", 'xlink:href', '#some-path');
label.appendChild(document.createTextNode("Hello, World!"));
label_container.appendChild(label);
g.appendChild(label_container);
svg.appendChild(g);
If you specify a path for your textPath
node (in red, above), you’ll need to use the setAttributeNS
function (as opposed to the setAttribute
function, as one (i.e. me) could mistakenly use).
In addition, when attempting to query the DOM for the textPath
element, ensure you create your textPath
elements with the proper case and your query selectors are case sensitive in WebKit browsers:
document.querySelector('textPath');
As an FYI, textPath
s are used to provide a path for which your text will follow. For example, if you wanted to show some text radially about a circle. The xlink
property is used to specify which textPath
that is defined will be used for a given text
node. Check out w3.org.