Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width from element using D3.js

This is my html:

<div class="bar no" style="width: 25.0916%;"></div>

I'd like to access the width size as a number or percentage.

I've tried some the following but the first returns nothing and the second returns the number in pixels.

width = this.getBBox().width

width = d3.select(this).style("width")

What can I use to return 500 or 25.0%?

like image 486
user3821345 Avatar asked Jul 23 '26 02:07

user3821345


1 Answers

Compare the following:

console.log('Computed style width as pixels: ');
console.log(d3.select('.bar').style('width'));
console.log('Computed style width as a number: ');
console.log(parseFloat(d3.select('.bar').style('width')));
console.log('As a percent: ');
console.log(d3.select('.bar').node().style.width);
console.log('Actual width as number: ');
console.log(d3.select('.bar').node().offsetWidth);
<script src="https://d3js.org/d3.v4.js"></script>
<div class="bar no" style="width: 25.0916%;"></div>
like image 179
Mark Avatar answered Jul 26 '26 05:07

Mark



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!