3

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%?

1 Answer 1

11

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Just out of curiosity: is there a reason you are doing the awkward document.write() instead of using console.log() to print to the snippet's console emulation? Good answer, BTW ;-)
@altocumulus, no reason. Just screwing around. I originally was going to color code things.
Holy moly! When I posted my first comment, I thought the use of document.write() was, well,... not that good. But changing the URL to a protocol-agnostic one takes it one step further ;-) Isn't that considered an anti-pattern nowadays? paulirish.com/2010/the-protocol-relative-url, jeremywagner.me/blog/stop-using-the-protocol-relative-url. Could you do the color coding for me, please ;-)
@altocumulus, are you watching this 9 month old post for changes? I'll edit again to make you happy :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.