javascriptelementoffsetwidth

OffsetWidth is always '0'


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


Solution

  • 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.