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.
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.
- I'm curious, why would you need to know programatically where the attribute was being set from? – Brian Hoover Commented May 11, 2012 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 Commented May 11, 2012 at 13:37
4 Answers
Reset to default 11I 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
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
}
You can use jQuery to search for the CSS height value and compare that?
<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>