0

I gave a div in my html file, a height of 100x and a width of 100px. I was trying to output the height using javascript, like this..

console.log(document.GetElementById("box").style.height);
// i gave the div an ID of box and styled it using css,but it console.logged an empty line.
https://i.stack.imgur.com/zVqEg.png

//But when i styled the div using css inline styling,it console.logged the height.
https://i.stack.imgur.com/biXZK.png

  • 2
    well that should be an error since it is not `GetElementById` It would help if you showed the html in the post of what worked, not an image of a console line. – epascarello Apr 23 '20 at 17:28
  • 1
    You really need to post the code yu are having troubles with, and be more specific on what issue you are having. – Stuart Apr 23 '20 at 17:30
  • 1
    [`getBoundingClientRect`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) – epascarello Apr 23 '20 at 17:31
  • @epascarello doesn't `getBoundintClientRect` return more information about the position of the element in the viewport? OP, `getElementById()` is the correct usage (no capital Get), but you need to post your HTML and CSS. – disinfor Apr 23 '20 at 17:35
  • 1
    An element’s `.style` property gives you the attributes of its `style="..."` attribute, not its computed style. – deceze Apr 23 '20 at 17:37
  • @disinfor why does it matter if it gives more than the height? – epascarello Apr 23 '20 at 17:47
  • @epascarello it doesn't matter...I was more curious. – disinfor Apr 23 '20 at 18:30

1 Answers1

0

Instead of reading the value of the style attribute, you need to get the computed height of your #box element.

There are a few ways to do this.

// includes height + vertical padding
var h = document.getElementById('box').clientHeight;

// includes height + top/bottom padding + top/bottom borders
var h = document.getElementById('box').offsetHeight;

// includes height of the contained document
// (possibly larger than mere height in case of overflow scrolling)
// + top/bottom padding + top/bottom borders
var h = document.getElementById('box').scrollHeight;

Also be sure you're calling getElementById() with a lowercase g at the beginning.

simmer
  • 2,639
  • 1
  • 18
  • 22