clb
clb

Reputation: 723

Property getBBox does not exist on type SVGElement

I'm using d3, and I'd like to use the getBBox method that SVG elements have.

I'm using the following: (d3Selection.node() as SVGElement).getBBox(), however the TypeScript fails to compile due to the error in the title.

Is SVGElement the wrong type to use? I can it working using any instead, but this seems like a bit of an "unclean" solution.

Upvotes: 5

Views: 8694

Answers (2)

Robert Longson
Robert Longson

Reputation: 123995

Not all SVG elements have bounding boxes, <defs> for instance doesn't, neither does <title>, so yes SVGElement is the wrong type to use. You want SVGGraphicsElement

Upvotes: 11

千木郷
千木郷

Reputation: 1807

Instead of SVGElement, SVGSVGElement is the correct type to use for accessing <svg> elements, where getBBox() method is available as well because of the inheritance from SVGGraphicsElement.

(d3Selection.node() as SVGSVGElement).getBBox()

Or if d3Selection is defined as

let d3Selection: D3.Selection<SVGSVGElement, {}, HTMLElement, any>
d3Selection.node().getBBox()

could be directly into usage.

Upvotes: 9

Related Questions