I am using the D3 library. I want to programatically select an element by its ID, but that ID includes a comma. I am reading the IDs in as part of the data, so I can't control that.
My code is:
g.nodes().forEach(function(v) {
d3.select('#'+v+)
.attr("cx", function(){return g.node(v).x; })
.attr("cy", function(){return g.node(v).y; })
});
Where v is a string that matches the ID.
Specifically, when I try d3.select("#B_ne_,3")
I get d3.js:562 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#B_ne_,3' is not a valid selector.(…)
.
I know that I can select it by using "#B_ne_\\\\,3"
, but how can I escape these characters in general?
I am NOT using jquery.
Use CSS.escape
(experimental as of May 2017):
var v = "B_ne_,3"; console.log("#" + CSS.escape(v));
There are exact polyfills for old browser, but it's simpler if you escape unnecessary characters:
var v = "B_ne_,3"; console.log("#" + v.replace(/\\W/g, '\\\\$&').replace(/^\\d/, '\\\\00003$&'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.