OffsetWidth is always '0'

960 views Asked by At

I'm stuck with something, while creating something. I want to set div's width and height to the same. So, I set div's width to 14% and the height of the div to the offsetWidth. So the div will be fully square in shape. But, offsetWidth is always 0. I've tried several things, but offsetWidth is zero.

Code


<body></body>

<script>

var elem = document.createElement('div');

elem.style.display = 'inline-block';

elem.style.backgroundColor = '#00B3FF';

elem.style.width = '14%';

elem.innerText = elem.offsetWidth;

document.body.appendChild(elem);

</script>

Fiddle

3

There are 3 answers

0
Mateusz On BEST ANSWER

All you have to do is place that piece of code:

document.body.appendChild(elem);

above the:

elem.innerText = elem.offsetWidth;

so it looks like this:

var elem = document.createElement('div');
elem.style.display = 'inline-block';
elem.style.backgroundColor = '#00B3FF';
elem.style.width = '14%';
document.body.appendChild(elem);
elem.innerText = elem.offsetWidth;

because the width is 0 until you append the div to the body.

0
Md iqbal On

I think some parent element has display: hidden or none. If the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.

Maybe this Doc can help: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

0
Joachim Damsgaard On

Is there a reason you don't use css? Useing aspect-ratio: 1/1 you will get the same result.

https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio