Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome returns 0 for offsetWidth of custom HTML element

While trying to create an Angular directive that adapts the size of its content to the size of the container, I stumbled over the following issue:

Minimal HTML snippet:

<my-tag id="testWidth">
  <div>some text</div>
</my-tag>

When reading the width of my-tag, I get a result of 0 in Chrome, whereas Firefox returns the correct result. In Chrome, the result is also correct if I replace my-tag by div.

This is the expression I use to get the width:

document.getElementById('testWidth').offsetWidth

As far as I know, my-tag should be a valid custom element name. Is there anything else that I am doing wrong, or is this simply a bug in Chrome?

Chrome version: 49.0.2623.112 m

jsfiddle for quick testing

I am trying to understand if the behavior of Chrome is correct or if this is a bug.

The MDN documentation says:

The HTMLElement.offsetWidth read-only property returns the layout width of an element.

As far as I can tell, it does not say that this only applies to elements with block display. And I also back my understanding by the fact that Firefox returns what I expect.

The same difference in behavior can also be observed for span tags, see this fiddle.

like image 370
ValarDohaeris Avatar asked Apr 21 '16 17:04

ValarDohaeris


People also ask

What is offsetWidth HTML?

The HTMLElement. offsetWidth read-only property returns the layout width of an element as an integer. Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered).

How do you find the height of an element in HTML?

The HTMLElement. offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer. Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered).

How do you find the width of a div?

To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels. Return Value: Returns the corresponding element's layout pixel width.


2 Answers

You need to style my-tag element with display: block

Here's fiddle https://jsfiddle.net/Lvntyrjy/1/

like image 132
Matti Mehtonen Avatar answered Sep 28 '22 19:09

Matti Mehtonen


You can also get the width of the content of the custom element like this:

document.querySelector('custom-element').shadowRoot.querySelector('#content').offsetWidth
like image 38
gitaarik Avatar answered Sep 28 '22 19:09

gitaarik