Search code examples
javascripthtmlcss

how can i get element height in javascript


I have tried this and it just brings an empty space in console of my browser. How can can i get the height of my element.

var background = document.getElementById('bgimage');
console.log(background.style.height);
.background {
  width: 100%;
  height: 500vh;
}
<div class="section s1">
  <div class="background" id="bgimage">
    .......
  </div>
</div>


Solution

  • Use offsetHeight:

    var background = document.getElementById('bgimage');
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    console.log(background.offsetHeight*100/h);
    .background {
    width: 100%;
    height: 500vh;
    }
    <div class="section s1">
    <div class="background" id="bgimage">
       .......
    </div>
    </div>

    Note: element.offsetHeight will return height of element in pixels (px).