3

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);
Community
  • 1
  • 1
haemse
  • 3,971
  • 5
  • 28
  • 40
  • as you can see i even set xml:space="preserve" to the svg element and the ... then the textnode ist appended to the tspan, the tspan to the text element and this to the svg ... however ... still contiguous whitespaces are elliminated ... fuuuuuuuuuuuuu – haemse Dec 08 '11 at 00:38

1 Answers1

13

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • Code can be indented by prefixing 4 spaces, inline code can be marked by surrounding backticks: \`Test\` -> `Test`. – Rob W Dec 08 '11 at 10:34
  • 2
    Thank you very much! You are an angel! :D Although i have to set the attribute to the tspan element itself, however it works now! – haemse Dec 08 '11 at 11:38