Search code examples
javascriptcssheightmargins

Javascript: Using element height as pixel value to set properties of other elements


I'm trying to set the height and margins of some elements based on the height of another, but it isn't working.

  function matchHeight(divName) {
    var Sheight = document.getElementById(divName).style.height;

    document.getElementById('bookmark').style.height = Sheight + '45px';
    document.getElementById('bookmarkend').style.marginTop = Sheight + '45px';
    document.getElementById('bookmarktagI').style.height = Sheight + '255px';
  }

What's wrong with my function?

I'd rather do it without jquery, if possible.


Solution

  • If your styles are set inline, i.e. <div style="height: 100px;"></div>, then most probably your problem is in parsing height style value. In this case Sheight will be "100px", which will simply concatenate with other values forming something like 100px45px, which isn't really good.

    To solve the problem parse the value to integer with parseInt and use correct addition:

    var Sheight = parseInt(document.getElementById(divName).style.height, 10);
    document.getElementById('bookmark').style.height = (Sheight + 45) + 'px';