Search code examples
javascripthtmltypescriptsvgd3.js

Get raw element from d3 selection


I'm building a custom visual for Power BI, written in TypeScript. In my class' constructor I write this.svg = d3.select(this.target).append("svg").attr("id", "svg"); (this.target just holds a standard HTML element, it's not important for the question).

My question is ,using this.svg, how can I obtain just the raw SVG element? From Googling it seems I should be able to use this.svg.node(), but there must be something subtle going on that makes this different to the "true" element...

When I run console.log(this.svg.node()), its output appears exactly the same as console.log(document.getElementById("svg")) in Chrome's developer window, so that's fine.

However, using the expression this.svg.node().getBoundingClientRect() causes my TypeScript to not compile because of the error Property 'getBoundingClientRect' does not exist on type 'Node', whereas document.getElementById("svg").getBoundingClientRect() returns the correct value.

How do I just get the true, raw DOM element that this.svg refers to?

I'm using d3 v3.


Solution

  • .node() is returning the real element, the problem here is that in other situations .node() can return other types of objects than just Elements, so the typescript compiler can't know it'll definitely have the getBoundingClientRect() function.

    The solution is to cast the object as type Element:

    var svgElement = this.svg.node() as Element;
    var boundingRect = svgElement.getBoundingClientRect();