Skip to content Skip to sidebar Skip to footer

Clientwidth Of Element Is 0 Unless I Set It With Css

How can I get an elements width without setting it's width property in CSS? If I set the width it works, but if I don't the width is just 0 even though I can see it's not after ins

Solution 1:

Use offsetWidth instead

let width = this.htmlElement.offsetWidth;

The first line in the docs for clientWidth is

The Element.clientWidth property is zero for elements with no CSS or inline layout boxes, otherwise it's the inner width of an element in pixels

The offsetWidth on the other hand is a read-only property that returns the layout width of an element, regardless of wether or not the element is styled with a given width.

var el = document.getElementById('foobar');

console.log('clientWidth : '+ el.clientWidth );
console.log('offsetWidth : '+ el.offsetWidth );
<labelid="foobar">This has width ..................</label>

Post a Comment for "Clientwidth Of Element Is 0 Unless I Set It With Css"