Reputation: 189
I need to set the height of an element equal to a div's height which height changes based on the elements inside it
I made this javascript code but it doesn't work.
What is wrong with it?
HTML
<div id="a" onclick="changeHeight();">
</div>
<div id="button">
</div>
JAVASCRIPT
function changeHeight() {
var divHeight = $("#a").height();
document.getElementById('button').style.height = divHeight;
}
CSS
#a{width:300px;height:100px;background-color:black;}
#button{width:300px;background-color:green;}
Upvotes: 0
Views: 542
Reputation: 874
Updated fiddle: https://jsfiddle.net/sne40vh1/3/
The main problem was that you were trying to set the height of #button
without a unit of measurement (jQuery's .height method returns only a value, no measurement) so when you were trying to set the style in the vanilla JavaScript, which requires a unit of measurement, it was failing (so in this case it would've needed '300px' but you were just giving it '300'.
I've changed it here to have a global function (which isn't recommended, I only did this for the fiddle to work) and changed the way you were setting the height of #button
to match the way you were getting the height of #a
:
HTML:
<div id="a" onclick="changeHeight()"></div>
<div id="button"></div>
CSS:
#a{width:300px;height:100px;background-color:black;}
#button{width:300px;background-color:green;}
JS:
changeHeight = function() {
var divHeight = $("#a").height();
$('#button').height(divHeight);
}
Feel free to compare what i've done with what you had in the first place in order to see my changes better.
Upvotes: 1
Reputation: 36609
Do concatenate with 'px'
(Unit)
function changeHeight() {
var divHeight = $("#a").height();
document.getElementById('button').style.height = divHeight + 'px';
}
#a {
width: 300px;
height: 100px;
background-color: black;
}
#button {
width: 300px;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="a" onclick="changeHeight();"></div>
<div id="button"></div>
Upvotes: 1
Reputation: 10776
Why are you mixing jQuery and vanilla Js? I wrote it completely with jQuery and it looks like it's working:
function changeHeight() {
var divHeight = $("#a").height();
$('#button').height(divHeight);
}
#a{width:300px;height:100px;background-color:black;}
#button{width:300px;background-color:green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a" onclick="changeHeight();">
</div>
<div id="button">
</div>
Upvotes: 1