Marwane Bettach Marwane Bettach - 1 month ago 14
HTML Question

javascript change height based on element's height

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?

jsfiddle

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;}

Answer

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.

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.