score:37

Accepted answer
<svg class="svg" height="3300" width="2550">
    <image x="0" y="0" height="3300" width="2550" xlink:href="1.jpg"></image>
    <rect class="word" id="15" x="118" y="259" width="182" height="28"
     text="Substitute"></rect>
</svg>

<script>
    var body = d3.select("body");
    console.log(body);
    var svg = body.select("svg");
    console.log(svg);
    console.log(svg.style("width"));
</script>

Just place your script after svg element is loaded by the browser and all will be fine.

score:-1

// HTML

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
        <svg width="950" height="500"></svg>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="index1.js"></script>
</body>
</html>

//JavaScript

const svg = d3.select('svg');

const width = +svg.attr('width');
const height = +svg.attr('height');
console.log(width)
console.log(height)

At this days this is what work for me.

score:2

If this svg is saved in a variable, for example:

var vis = d3.select("#DivisionLabel").append("svg")
    .attr("width", "100%")
    .attr("height", height);

Then directly one can use the variable vis to get the width of svg by:

console.log(vis.style("width"));

The result is in unit "px". Pay attention that vis.style("width") returns a string.

score:3

You will end up with value "auto" unless you initialize the values of the attributes (width), I would recommend the below instead.

d3element.getBoundingClientRect().width;

or

var element = d3.select('.ClassName').node();
element.getBoundingClientRect().width;

score:4

Try using svg.attr("width"). It just gives a plain number string.

score:7

var svg = d3.select("body")
                .append("svg")
                .attr("width",  "100%")
                .attr("height", "100%");

var w = parseInt(svg.style("width"), 10);
var h = parseInt(svg.style("height"), 10);

score:18

if you have an SVG element w/ id=frame...

 frame = d3.select('#frame')
                     .attr('class', 'frame')

            fh = frame.style("height").replace("px", "");
            fw = frame.style("width").replace("px", "");

fh and fw can now be used in math expressions.

you can also drop back to jQuery

  fw = console.log($("#frame").width());
  fh = console.log($("#frame").height());

which are numbers and can be used in math expressions


Related Query

More Query from same tag