Tomohiro Koana Tomohiro Koana - 2 months ago 9
Javascript Question

Using getStartPositionOfChar (or getEndPositionOfChar) on SVG text element with a white space

I am trying to use

getStartPositionOfChar
on a SVG
text
tag that contains only one white space:

SVG

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300">
<text id="t"> </text>
</svg>


JS

var t = document.getElementById('t');
var sp = t.getStartPositionOfChar(0);


Although it works fine when the
text
tag has a non-space character, it seems to trim white space, resulting in
IndexSizeError
.

https://jsfiddle.net/tomohiro_1221/7bmefec7/

Is there a workaround for this? I would like to obtain the start position (or end position) when it has only a white space.

Answer

You could disable whitespace compression by using xml:space="preserve" (SVG 1.1) or CSS white-space: pre; (SVG 2)

var t = document.getElementById('t');
var sp = t.getStartPositionOfChar(0);
console.log(sp);
svg {
  white-space: pre;
}
 <svg xmlns="http://www.w3.org/2000/svg" width="300" height="300">    
   <text id="t"> </text>
 </svg>