0

let a = document.getElementsByClassName("d1");
let b = window.getComputedStyle(a[0]);
let c = b.getPropertyValue("height");
alert(c);
.d1 {
  background-color: red;
  padding: 20px;
}
<div class="d1">Test test test</div>

The above code alerts 18px but the height of the div element is actually 48px. It looks like that it doesn't take in consideration its padding. How can I alert its real height?

darkchampionz
  • 1,174
  • 5
  • 24
  • 47

1 Answers1

1

The CSS height property does not include padding. Try using .clientHeight instead, which does include padding. Here's from the docs:

clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present).

let a = document.getElementsByClassName("d1");
let c = a[0].clientHeight;
alert(c);
.d1 {
  background-color: red;
  padding: 20px;
}
<div class="d1">Test test test</div>
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Far more discussion in the flagged duplicate. Please take the time to flag basic questions for closure as they more often than not have the benefit of multiple answers offering a greater range of explanation and possible solutions. – pilchard Jan 30 '23 at 01:17
  • @pilchard I'd say this question is kind of an edge case ([signpost dupe](https://stackoverflow.blog/2009/05/20/linking-duplicate-questions/) maybe?). Sure, the dupe you flagged happens to have the same answer, but the questions are different. The dupe asks how to do something but this question asks for help with a bug, so it's certainly not just a useless carbon-copy. – Michael M. Jan 30 '23 at 01:26
  • The question here boils down to *'How can I alert its real height?'* (in the OPs own words) which seems as a clear a dupe of *'Get div height with plain JavaScript'* as one could ask for. – pilchard Jan 30 '23 at 09:02