5

To preserve spaces in a textelement of svg, one should use 'xml:space="preserve"' as an attribute of the text (jsfiddle). However, it isn't working. What am I doing wrong?

    // init snap
    var svgElement=document.getElementById("mainSvgId");
    var s = Snap(svgElement).attr({height: 300, width: 300});

    // greate group with rectanle
    var parentGroup=s.g().attr({id: "parent"});
    var rect1 = s.rect(0, 0, 200, 200).attr({fill: "#bada55"});
    parentGroup.add(rect1);

    // add text with preserve attribute
    var text = s.text(0, 20, "   text1    text2");
    text.node.setAttribute("xml:space", "preserve");
    parentGroup.add(text);
user3756754
  • 65
  • 1
  • 5

1 Answers1

7

You're almost there. You need to properly create the attribute in the xml namespace for which you need setAttributeNS rather than setAttribute

text.node.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve");
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • 2
    This is apparently [deprecated](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xml:space). You're meant to use [CSS whitespace](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) now. – Timmmm Jan 02 '17 at 17:45
  • @Timmmm original solution by Robert works. Does CSS `whitespace: pre` has the same behavior as xml:space attribute? – Alleo Oct 13 '22 at 08:44