20

I have 2 divs:

<div id="div1"></div>
<div id="div2">div2</div>​

in my css:

#div1{ height:20px}​

Both divs have 20px height, check demo
How can I find out if the div have it's height due to content or have been set in css or inline style?
This helps me find out the dimensions have been set by the developer or just calculated by the browser.

ilyes kooli
  • 11,959
  • 14
  • 50
  • 79
  • I'm curious, why would you need to know programatically where the attribute was being set from? – Brian Hoover May 11 '12 at 13:36
  • If the height have been set with css or an inline style, then my plugin don't have the right to override it, otherwise I can override it – ilyes kooli May 11 '12 at 13:37

4 Answers4

11

I found a way to achieve it :)

function getRealHeight(element){
    var height=0;
    if (element.children().length>0){
        var temp = $('<div></div>');
        temp.append(element.children());
        height = element.height();
        element.append(temp.children());
    } else {
        var html=element.html();
        element.html('');
        height = element.height();
        element.html(html);
    }
    return height;
}

DEMO

ilyes kooli
  • 11,959
  • 14
  • 50
  • 79
2

Use this function:

function emptyHeight ( elem ) {
    var $temp = $( '<div />' );
    var $elem = $( elem );
    var height;

    $temp.append( $elem.contents() );
    height = $elem.height();
    $elem.append( $temp.contents() );

    return height;   
}

The idea is to temporarily detach all child nodes from the element. An element with no children has a height of 0, unless its height is set via CSS.

Pass your DIV element into that function. If it returns 0, that means that the DIV does not have its height set via CSS.

if ( emptyHeight( yourDiv ) === 0 ) {
    // the DIV does not have any height value set via CSS
} else {
    // the DIV has a CSS height set
}
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
1

You can use jQuery to search for the CSS height value and compare that?

Robert
  • 1,899
  • 1
  • 17
  • 24
1
<div id="div-styled" style="height: 20px"></div>
<div id="div-unstyled"></div>

Check for inline CSS height property with plain JavaScript

document.getElementById('div-styled').style.height // "20px"
document.getElementById('div-unstyled').style.height.length // 0

Update

jQuery returns style rules from external style sheets as well with .css()

var $el = $('#container');
$el.html( $el.css('height') );
#container {
  height: 42px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="container"></div>
sshow
  • 8,820
  • 4
  • 51
  • 82