Skip to content
Advertisement

Get innerWidth() equivalent without jQuery

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement