4

I have

<text id="element.id.with.dots" x="10" xml:space="preserve" y="10" stroke="none">

How can I select it using d3.select? This doesn't seem to work, it returns null

var textElem = d3.select("text[id=element\\.id\\.with\\.dots]");

and this :

var textElem = d3.select("text[id=element.id.with.dots]");

gives me error in Firebug console window:

SyntaxError: An invalid or illegal string was specified
Benas
  • 2,106
  • 2
  • 39
  • 66
  • 3
    This may help you: http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Finrod Nov 03 '15 at 15:24

2 Answers2

12

Use a quoted string to delimit the value of your attribute:

var textElem = d3.select("text[id='element.id.with.dots']");

var el = d3.select("text[id='element.id.with.dots']");
el.style({fill: 'red'})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg>
     <text id="element.id.with.dots" x="10" xml:space="preserve" y="10" stroke="none">Text/<text>
</svg>
nikoshr
  • 32,926
  • 33
  • 91
  • 105
0

Another solution would be to escape each period by putting a backslash \ before it—then you can use d3.select() or d3.selectAll() as usual.

You can use .replace(/\./g, '\\.') to add the backslashes automatically.

Remember (thanks, altocumulus!), to escape the backslashes themselves with another backslash if you're editing the id manually.

d3.select("#element\\.id\\.with\\.dots")

Community
  • 1
  • 1
Randoms
  • 2,110
  • 2
  • 20
  • 31
  • Don't forget to add double backslashes when passing the string into `d3.select()`. It's the same you are doing in your `.replace()`. https://jsfiddle.net/vL7360rn/2/. You want the backslash in the string and, therefore, need to escape it with the second backslash. If you miss out the second one, the single backslash will escape the following dot instead. – altocumulus Mar 23 '17 at 12:20
  • @altocumulus can't believe I forgot that—thanks. Answer has been edited accordingly. – Randoms Mar 25 '17 at 01:35