Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.select is not working with special Characters

I am working on simple chart using d3.js.Assume following div where i planned to place my svg container of d3

<div id="my~div_chart">

But when i use

d3.select('#my~div_chart')

I am not able to select particular div, however by using java script selector,its working.

document.getElementById("my~div_chart");

Can anyone suggest me why this is happening.if it is a special character issue,tell me what are the special characters supported.

like image 446
PraveenKumar S Avatar asked Dec 23 '16 06:12

PraveenKumar S


1 Answers

It's right there, in the specifications:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F". (emphasis mine)

Besides that, ~ is a sibling combinator:

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

So, if you still want to use that ID, you have to escape the tilde, using "#my\\~div_chart":

d3.select("#my\\~div_chart").on("click", function(){
    d3.select(this).style("background-color","teal")
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="my~div_chart">Click Me</div>

Finally, in your question, you said that document.getElementById worked. However, have in mind that document.querySelector would fail.

like image 175
Gerardo Furtado Avatar answered Sep 19 '22 15:09

Gerardo Furtado