PDA

View Full Version : Get an element's computed line-height



David Sudweeks
01-08-2010, 03:14 PM
If I want to find the line-height associated with an element such as a div, I can get it using document.getElementById('div_name').style.lineHeight, but only if it's been set for that specific element (It won't return an inherited value from its parent element, instead it just returns an empty string).
Example: If I set text in Georgia at 14px with a line height of 1.56em, I can use Firebug to tell me the computed style's line-height is 21.833px (in Firefox of course).
Is there any way to get that same value with JavaScript?

jscheuer1
01-08-2010, 04:02 PM
Varies by browser, and you will get various values as well, as far as whether they are expressed as pixels (with or without decimals), points, 'normal' (at times if there's none explicitly set for it anywhere), perhaps others.

That said, here's a demo:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
a {
display: inline-block;
background-color: #000;
color: #fff;
line-height: 120%;
}
a:hover {
background-color: #fff;
color: #000;
}
</style>
</head>
<body>
<a id="test" href="#">Test</a>
<script type="text/javascript">
(function(){
var dash = /-(.)/g;
function toHump(a, b){return b.toUpperCase();};
String.prototype.encamel = function(){return this.replace(dash, toHump);};
})();

function getStyle(el, styleprop){
el = document.getElementById(el);
if(window.getComputedStyle){
return document.defaultView.getComputedStyle(el, null).getPropertyValue(styleprop);
}
else if(el.currentStyle){
return el.currentStyle[styleprop.encamel()];
}
return null;
}

alert(getStyle('test', 'line-height'));
</script>
</body>
</html>

Note: For the IE family of browsers, this requires IE 5.5+ or there will be an error. For all others, including IE 5.5+ it will return some value or, if it cannot use either of the two methods, null.

David Sudweeks
01-08-2010, 04:23 PM
This is precisely what I was looking for. Thank you.