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;}
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>
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>
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.