jQuery: Why does .width() sometimes return 0 after inserting elements with .html()?

jQuery will return a zero width if the element is not visible. For example, I was having the same issue with an item being inserted onto a hidden form tab. Temporarily assigning it to the body, where it was visible, I was able to determine the width:

$("body").append(el); // First assign it to the body so that it's visible
var width = el.width(); // The width will now be correct
wrapper.append(el); // Now place the element where you want it.

One caveat is that if the element inherits different styling when assigned to the body then the width may not be correct.


Depends on what browser. Occasionally I find something will break with the synchronous rendering expectations of the javascript runtime and I'll need to get the result on the next tick.

I'd try:

$(elem).html(data);
setTimeout(function(){
    // Get the width here
},0);

We found out that document.ready was not good enough so 300ms worked well:

    setTimeout(function() {
        resizeHeightOfMyDiv();

        $(window).on("resize", function() {
            resizeHeightOfMyDiv();
        });
     }, 300);

Tags:

Jquery