Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the type of element in a selection

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

enter image description here

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!

like image 349
mrbrahman Avatar asked Oct 20 '25 21:10

mrbrahman


1 Answers

There are a couple of ways to determine the type of a DOM element:

  1. 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"   
    
  2. 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"
    
  3. You can make use of the well-known symbol Symbol.toStringTag to access the element's interface name:

    element.node()[Symbol.toStringTag] === "SVGSVGElement"
    
  4. 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>
like image 169
altocumulus Avatar answered Oct 22 '25 13:10

altocumulus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!