0

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?

Pieter
  • 38
  • 9

2 Answers2

0

EDITED ANSWER

DEMO

$('#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>').css({
        position: 'absolute',
        top: -9999,
        left: -9999
    }).appendTo('body');



    var ret = {
        width: $html_calc.width(),
        height: $html_calc.height(),
    };
    $html_calc.remove();

    return ret;
}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • Because I want the width/height of the html within a element. With your solution I get the size of the element itself, not what's in it: http://jsfiddle.net/qJ6BZ/ – Pieter Jun 30 '13 at 15:22
  • See updated answer but of course this will return same size as the container as DIV adapt width & height to its content except if some CSS rule are applied as padding/border/etc... If still not working as you expect, please consider to tell what size in this case you are expecting for the content – A. Wolff Jun 30 '13 at 15:45
0

When you copy a hidden element it's size is zero. Just unhide it for the calculation:

function elementSize ( elementId ) {
    ...
    $( elementId ).html( html_calc ).show();    
    var ret = {
        ...
    };    
    $( elementId ).html( html_calc ).hide();    
    ...    
    return ret;
}
Martin Mandl
  • 721
  • 3
  • 11
  • Thanks Martin for your reply but it still doesn't work yet: http://jsfiddle.net/psqM9/ Or am I doing something wrong here? – Pieter Jun 30 '13 at 15:27
  • I just added .show() before the calculation, and *.hide() afterwards, have a look http://jsfiddle.net/psqM9/1/ – Martin Mandl Jun 30 '13 at 18:35