D3.select does not work with special characters

I am working on a simple diagram using d3.js.Assume after the div where I planned to host my d3 svg container

<div id="my~div_chart"> 

But when I use

 d3.select('#my~div_chart') 

I cannot select a specific div, however, using the java script selector, its working.

 document.getElementById("my~div_chart"); 

Can someone tell me why this is happening. If this is a special issue, tell me which special characters are supported.

+6
source share
1 answer

It is right there in the specification :

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

In addition, ~ is a combinator:

A common combinator consists of the tilde character (U + 007E, ~), which separates two sequences of simple selectors. Elements represented by two sequences share the same parent element in the document tree, and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second.

So, if you still want to use this identifier, you need to avoid 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 document.getElementById worked. However, keep in mind that document.querySelector will fail.

+5
source

Source: https://habr.com/ru/post/1013455/


All Articles