Benas
Benas

Reputation: 2332

D3 how to select element by ID when there is a dot in ID

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

Upvotes: 4

Views: 4299

Answers (2)

Randoms
Randoms

Reputation: 2120

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")

Upvotes: 0

nikoshr
nikoshr

Reputation: 33344

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>

Upvotes: 12

Related Questions