I want to be able to calculate the width, in pixels, of an element that has the width css property set to 'auto'
.
I have tried element.style.width
but didn't work because it returned 'auto'
. I notices that the jQuery function width()
returns the length in px, but I cannot use jQuery to solve this, because it is not available in my page. So, does anybody know an equivalent method for jQuery width()
?
Thanks.
Wasted 2 hours on this.
For my case other answers did not work so combining others answers & my findings into one post with examples, for easy reading:
For an element like select
, the width()
in JQuery is same as clientWidth
in JavaScript.
Sample code below, including output:
// Add jQuery library in HTML:
// <head>
// <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
// </head>
let eleId = 'myselectid1'; // NOTE: Provide your element id below
// jQuery
console.log( $('#' + eleId).width() );
// JavaScript
let ele = document.getElementById(eleId);
console.log(ele.clientWidth); // 58 // includes padding into calculation
console.log(ele.offsetWidth); // 60 // includes border size and padding into width calculation
console.log(ele.getBoundingClientRect().width); // 60 // includes border size and padding into width calculation
console.log(window.getComputedStyle(ele, null).getPropertyValue("width")); // 60px (note the px in value, you may also get values like 'auto') // all dynamic values for all CSS properties, IE>=9
console.log(ele.style.height); // empty string // if you set it earlier, you would get this
console.log(ele.innerWidth); // undefined // only works on window object, not on element like select/ div - fails in older IE<9
Hope that helps.
jQuery uses...
element.getBoundingClientRect().width
internally, it has some other stuff on top to deal with browser differences.
It returns an elements rendered size, where as .offsetxx returns sizes according to the box model.
element.getBoundingClientRect()
Is the most accurate way to get an elements "real" dimensions.
Here is a post by John Resig ( author of jQuery ) on the matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With