1

How do I determine the width of an auto sized element (no specified width)?

In example I need to determine the width of a span element.

The following do not work:

getElementsByTagName('span')[0].clientWidth;
getElementsByTagName('span')[0].getBoundingClientRect().width;
getElementsByTagName('span')[0].offsetWidth;

When looking at the Chrome developer console / computed tab the graph shows "auto x auto".

Chrome version 49.0.2623.87 m bug?

No frameworks.


Turns out that in Chrome if a parent element is set to display: none all the properties will return as 0 which is incredibly lame.

John
  • 1
  • 13
  • 98
  • 177
  • Impossible.... `getBoundingClientRect` *should* give you the needed result – Roko C. Buljan Mar 17 '16 at 20:21
  • @RokoC.Buljan If it did then I wouldn't be forced to inquire. :-\ – John Mar 17 '16 at 20:24
  • open console (Developer Tools) and see the listed errors please. Cause getBoundingClientRect is a genie/beast on his own and it has to work! – Roko C. Buljan Mar 17 '16 at 20:29
  • I have the same version of Chrome, and `getBoundingClientRect` still works for me... – Hatchet Mar 17 '16 at 20:30
  • @RokoC.Buljan It is which is why I went to my own code and copied it. This works in Firefox fine though not Chrome? I've got a big cloud of WTH over my head right now and a hard deadline. :-\ – John Mar 17 '16 at 20:31
  • @John believe me. You can reliably trust getBoundingClientRect if you read my answer example especially. And if your in a burning deadline - than you **should** use more often the Developer Console to prevent stupid bugs snitch unnoticed – Roko C. Buljan Mar 17 '16 at 20:33

2 Answers2

1

As has been mentioned in the comments, your getBoundingClientRect() snippet ought to work.

Otherwise, try offsetWidth instead of clientWidth.

For more information about offsetWidth and other properties like it, see this answer: https://stackoverflow.com/a/21064102/2773837

Community
  • 1
  • 1
Hatchet
  • 5,320
  • 1
  • 30
  • 42
1

As I said in comments: it has to work!

var spanBCRw = document.getElementsByTagName('span')[0].getBoundingClientRect().width;

console.log( spanBCRw );   // 7.09375
<span>a</span>

Most probably you forgot to first target document where the DOM is stored

http://jsbin.com/nukufi/edit?html,css,js,console,output


var doc = document; // !!!!!!!!!!

console.log(
  doc.getElementsByTagName('span')[0].clientWidth, // 0 
  doc.getElementsByTagName('span')[0].getBoundingClientRect().width, // 7.09375
  doc.getElementsByTagName('span')[0].offsetWidth // 8
);

clientWidth will work only if you set your span to CSS:
display:inline-block; or display:block;

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Updated the question to reflect the problem I encountered so other people who have the same issue will have something to go on. – John Mar 17 '16 at 20:56