Reputation: 4273
Im trying to add some text that contains several whitespaces to a svg text element. I'm totally desprate, because when there is more than one whitespaces after an other they are added correctly to the element but do not show up in the browser window.
This guy here uses whitespaces in the text element and it works fine when i reproduce it static, but when adding the text with js the whitespaces disappear!
Significant whitespace in SVG embedded in HTML
How can i add text with whitespaces dynamically to a svg?
Thx for any answer!
var legend = document.createElementNS("http://www.w3.org/2000/svg", "text");
var tspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
// Set any attributes as desired
legend.setAttribute("id","legend");
legend.setAttribute("text-anchor", "middle");
legend.setAttribute("alignment-baseline", "hanging");
legend.setAttribute("xml:space","preserve");
tspan.setAttribute("xml:space","preserve");
tspan.setAttribute("id","tspanObj");
var myText = document.createTextNode(legendTxt);
tspan.appendChild(myText);
legend.appendChild(tspan);
legend.setAttribute("x", Math.round(this.options.windowWidth/2));
legend.setAttribute("y", this.options.upperPadding+this.options.barH+this.options.legendDist);
this.elements.jSvgElem.append(legend);
Upvotes: 3
Views: 7483
Reputation: 124089
You need to use setAttributeNS
to set an attribute in the xml namespace so in your case...
legend.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space","preserve");
If xml:space
is set on the text, the child tspan will use that value so you don't need to set it again in your case.
Upvotes: 13