Javascript equivalent for jquery width ()

I need to know the width in pixels of an element that has a width css property set to 'auto'. I tried element.style.width, but did not work because it returned "auto". I notice that the jquery width () function returns the length in px, but I cannot use jquery to solve it, because it is not available on my page. So does anyone know the label equivalent for jquery width ()?

Thanks.

+8
javascript jquery css width
source share
3 answers

It basically comes down to .offsetWidth , but jQuery code is a bit more complicated due to differences between browsers.

+1
source share

jQuery uses ...

 element.getBoundingClientRect().width 

internally, he has something else to deal with browser differences.

It returns the size created by the elements, where asoffsetxx returns the sizes according to the box model.

 element.getBoundingClientRect() 

It is the most accurate way to get elements of "real" dimensions.

Here is a post by John Resig (jQuery author) on this subject.

+13
source share

It took 2 hours.
Other answers were incorrect for my case.
Comparing all the other answers in one post, adding my results with examples:

width() in jQuery
same as
clientWidth in JavaScript
for an element of type select

Sample code below, including output:

 // NOTE: Give you element id below let eleId = 'myselectid1'; // 58 // includes padding into calculation // <head> // <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> // </head> // To enable below/jQuery, you would need above in HTML // alert( $('#' + eleId).width() ); // 58 // includes padding into calculation a = document.getElementById(eleId).clientWidth; alert(a); // 60 // includes border size and padding into width calculation a = document.getElementById(eleId).offsetWidth; alert(a); // 60 // includes border size and padding into width calculation a = document.getElementById(eleId).getBoundingClientRect().width; alert(a); // 60px (note the px in value, you may also get values like 'auto') // all dynamic values for all CSS properties, IE>=9 a = window.getComputedStyle(document.getElementById(eleId), null).getPropertyValue("width"); alert(a); // empty string // if you set it earlier, you would get this a = document.getElementById(eleId).style.height; alert(a); // undefined // only works on window object, not on element like select/ div - fails in older IE<9 a = document.getElementById(eleId).innerWidth; alert(a); 

Hope this helps.

0
source share

All Articles