How can I find the underlying element of a d3 selection?
I tried d3.select(elem).node()
gives the entire node, not just the element. I also checked (in v5) that there is a _groups
, and I could potentially derive the element from there. But is there a more direct method?
Edit
For e.g.
var svg = d3.select('svg');
renderChart(svg);
...
var g = d3.select('g');
renderChart(g);
function renderChart(element){
// I want to find out here if the element (selection) passed
// is "svg" or a "g", and then take appropriate action
// element.node() is giving me the whole object -- not just that particular element
if (<tbd> == "svg"){
// take action here
}
}
element.node()
in the above example returns an object. For e.g. in case of svg
, it looks like this in Chrome console
In my real case, I have the main chart that I have to draw on SVG element, but I need to provide clickable actions on that chart, which will run the same chart code, but with different data to generate a "sub chart" and append it as "g" element.
Thank you!
There are a couple of ways to determine the type of a DOM element:
For any type of node you can always get the name of the node by reading Node.nodeName
. In your example:
element.node().nodeName === "svg"
If you know that your node is an element type you can refer to the specific interface's property Element.tagName
:
element.node().tagName === "svg"
You can make use of the well-known symbol Symbol.toStringTag
to access the element's interface name:
element.node()[Symbol.toStringTag] === "SVGSVGElement"
The most typesafe way will be to directly compare the element's constructor to the DOM interface:
element.node().constructor === SVGSVGElement
Here is the executable demo for all the above approaches:
const element = d3.select("svg");
console.log(element.node().nodeName === "svg");
console.log(element.node().tagName === "svg");
console.log(element.node()[Symbol.toStringTag] === "SVGSVGElement");
console.log(element.node().constructor === SVGSVGElement);
<script src="https://d3js.org/d3.v5.js"></script>
<svg></svg>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With