6

I have two divs, neither have a height set in css, as I want to take whatever height they end up as and set the other div to be that height.

The javascript I have is this

function fixHeight() {
    var divh = document.getElementById('prCol1').height;
    document.getElementById('prCol1').innerHTML = '<ul><li>' + divh + '</li></ul>';
    document.getElementById('prCol2').style.height = divh + 'px';
}

I have the following line of code just to see if I am getting some kind of actual response.

document.getElementById('prCol1').innerHTML = '<ul><li>' + divh + '</li></ul>';

I have a onload set to run the function

my two divs look like this

<div id="prCol1">
     ..content..
</div>
<div id="prCol2" class="slideshow">
    ..content..
</div>

5 Answers5

10

Use offsetHeight - http://jsfiddle.net/HwATE/

function fixHeight() {
    var divh = document.getElementById('prCol1').offsetHeight; /* change this */
    document.getElementById('prCol1').innerHTML = '<ul><li>' + divh + '</li></ul>';
    document.getElementById('prCol2').style.height = divh + 'px';
}
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
  • I don't believe offsetHeight is fully supported by all browsers. I haven't done indepth research on if jQuery fixes the issues but that's the point of it right? http://vadikom.com/dailies/offsetwidth-offsetheight-useless-in-ie9-firefox4/ – John Culviner Jun 13 '12 at 04:13
  • @JohnCulviner Yes, it might cause a `1px` difference, but in the OP's case it's not really relevant, I think. His goal is to make the 2 `
    `-s equally high and exactly that will happen. I believe that's the possibility(it might even not happen) of `1px` difference in IE9 is a good trade-off for not including a 40K library(if it's not already included). And raw JS is always faster.. And `offsetHeight` is supported in every browser - http://www.quirksmode.org/dom/w3c_cssom.html
    – Zoltan Toth Jun 13 '12 at 12:25
2

You can use jQuery to get the height and set it.

var h = $("#prCol1").height();
$("#prCol2").height(h);
Ryan
  • 1,797
  • 12
  • 19
2

you can get height by this code:

document.getElementById('YourElementID').clientHeight;
S. V
  • 1,085
  • 5
  • 5
0

There are jQuery plugins to do this in a general way. Here's one.

kevin cline
  • 2,608
  • 2
  • 25
  • 38
0

I would recommend using jQuery here. You can't get the height of an element like you are trying in any browser I know of. Here is the code if you use jQuery which is very straightforward. I wouldn't try to do this without jQuery because browsers can be different in respect to how you access height.

function fixHeight() {
    var $prCol1 = $('#prCol1');
    var divh = $prCol1.height();
    $prCol1.html('<ul><li>' + divh + '</li></ul>');
    $('#prCol1').height(divh);
}
John Culviner
  • 22,235
  • 6
  • 55
  • 51