I'm trying to get the width & height of a element with jQuery. Now I have a function that wraps a span around the element and gets the size from the temporary span element.
HTML
<a id="test">click</a><br />
<div id="content" style="display:block">
<div>Hello world</div>
</div>
<h3>Result:</h3>
<div id="result"></div>
JS
$( '#test' ).click ( function () {
var size = elementSize ( '#content' );
$( '#result' ).html ( size.width + ' x ' + size.height + ' px' );
} );
function elementSize ( elementId ) {
var html_org = $( elementId ).html ();
var html_calc = '<span>' + html_org + '</span>';
$( elementId ).html( html_calc );
var ret = {
width: $( elementId ).find( 'span:first' ).width (),
height: $( elementId ).find( 'span:first' ).height (),
};
$( elementId ).html( html_org );
return ret;
}
An (not) working example: http://jsfiddle.net/KmeaC/1/
The only way to get the actual width & height of "Hello world" is to remove the div tags around it: http://jsfiddle.net/ycxTr/. But that is not what I want :)
Anyone?