Reputation: 7577
I have two divs side by side. Neither of them has a standart height, but the first one has content when the other one fill with content after a form submition. I want to set the height of the second one the same with the first one.
Here is the html:
<div id='left'>
...........
</div>
<div id='right'>
...........
</div>
<script type="text/javascript">
$(document).ready ( function(){
var divHeight = document.getElementById('left').style.height;
document.getElementById('right').style.height = divHeight+'px';
});
</script>
I don't have any error on the console, but the height of the second div doesn't change. Any help?
Upvotes: 9
Views: 13376
Reputation: 477
I created a helper function that accepts a jquery object with multiple objects to set the height equal. check it out...https://gist.github.com/rob-bar/10283279 Advantages are that the functionality is isolated so you can make a list of things to check when you have more divs than 2 or divs in divs that you want ....etc...
BUT! be aware of the fact that you can accomplish equal heights with either flexbox or with display: table and cell on the child.
Upvotes: 0
Reputation: 4134
You're looking for the offsetHeight
. The height
property of your leftmost div is not set (because that's the actual CSS property, and you're not setting the height statically), but the offsetHeight
is the actual height of the div as defined by its contents.
var offsetHeight = document.getElementById('left').offsetHeight;
document.getElementById('right').style.height = offsetHeight+'px';
Here's a jsFiddle to demonstrate.
Note that there is also clientHeight
. The difference is that offsetHeight
also includes padding and borders. See this answer as well.
Upvotes: 13
Reputation: 3563
I see you're using jQuery. Here's the jQuery version that is equivalent of the native JavaScript code that you used.
$(document).ready ( function(){
var divHeight = $('#left').height();
$('#right').height(divHeight);
});
Since you're using left
and right
as the elements' Id, I assume they are inline-block
s. So you should set the offset height of the other one than the real height :
$(document).ready ( function(){
var divHeight = $('#left')[0].offsetHeight;
$('#right').height(divHeight);
});
Upvotes: 0
Reputation: 5716
With jQuery
$(document).ready ( function(){
var leftHeight = $('#left').height();
$('#right').height(leftHeight);
});
or directly
$(document).ready ( function(){
$('#right').height( $('#left').height() );
});
Upvotes: 0