Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Get the width of an undefined element

I have a div element, that has no defined width or height. It holds other elements, and molds on their size. I need to get the final size of the div, without being able to check the sizes of the elements inside of it (dynamic elements).

I tried parsing all the properties of the object, but found nothing, all were "undefined".

Any thoughts?

Many thanks

Later edit:

I have

<div id="xxx" style="position:relative;">  
    aaaa
</div>

I tried:

var a = mydiv.style.width;

But it did not work.

I also tried:

var getKeys = function (obj) {  
    var keys = [];

    for(var key in obj){  
        document.write(key+"="+obj.key+"<br>");  
    }  

    return keys;  
}  

getKeys(mydiv.style);  

To show all the properties, but none had any info.

The jQuery solution works perfectly, but getComputedStyle was what I was looking for, as I can't use jquery here.

Sorry for the short information.

like image 578
Dilvish5 Avatar asked Oct 29 '25 05:10

Dilvish5


1 Answers

Based on no information whatsoever about what you were doing, I'd suggest that you should (if possible) use the window.getComputedStyle() approach, which finds the properties of an object as rendered by the browser:

var elem = document.getElementById('elemId'),
    properties = window.getComputedStyle(elem, null),
    height = properties.height,
    width = properties.width;

If you have jQuery available, then you can simply use the width() and height() (or outerWidth()/outerHeight()) methods:

var height = $('#elem').height(),
    width = $('#elem').width();
like image 78
David Thomas Avatar answered Oct 30 '25 20:10

David Thomas