Marwane Bettach Marwane Bettach - 1 year ago 125
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?



<div id="a" onclick="changeHeight();">
<div id="button">


function changeHeight() {
var divHeight = $("#a").height();
document.getElementById('button').style.height = divHeight;



Answer Source

Updated fiddle:

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:


<div id="a" onclick="changeHeight()"></div>
<div id="button"></div>




changeHeight = function() {
  var divHeight = $("#a").height();

Feel free to compare what i've done with what you had in the first place in order to see my changes better.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download