Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get innerWidth() equivalent without jQuery

Tags:

javascript

I'm currently working on eliminating jQuery from some code that I've written, and I've got a portion of code in which I was computing both the inner and outer widths of some span elements. It seems like .getBoundingClientRect() works fine for getting the outer width of an element, but I'm a bit stuck on getting the inner width. (i.e. the width of the element sans padding and borders.)

I'm using d3 to create my spans, and I need to compute their inner widths so that I can effectively set the widths of some other elements in order to get them to line up. Is there a good way of getting inner width for a div without manually checking and subtracting the various .css properties that could affect it?

like image 408
ckersch Avatar asked Dec 23 '13 17:12

ckersch


2 Answers

Not sure how stable this is, but the method that seems to be working is using window.getComputedStyle(element).width.

This gives the computed style as "95px", where 95 is the inner width (in pixels). I'm using parseInt(window.getComputedStyle(element).width) to get the inner width of the element as a number.

like image 181
ckersch Avatar answered Sep 17 '22 22:09

ckersch


You could try .offsetWidth. Here's a fiddle.

like image 44
Justin Chmura Avatar answered Sep 21 '22 22:09

Justin Chmura