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>
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>
Share
Improve this question
edited May 18, 2020 at 6:21
asked Nov 30, 2019 at 10:01
user12424171user12424171
2
- 2 Does this answer your question? How do you get the rendered height of an element? – BadPiggie Commented Nov 30, 2019 at 10:04
-
element.style.height
refers to inline style only. – connexo Commented Nov 30, 2019 at 15:12
4 Answers
Reset to default 5Use 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
).
An element's clientHeight is a measurement that includes the element CSS height and the element vertical padding and, if rendered, subtracting the height of the horizontal scrollbar.
try background.clientHeight
Just fix your javascript code
var background = document.getElementById('bgimage');
var bgimage = getComputedStyle(background);
console.log(bgimage.getPropertyValue('height'));
This is my function to get offsetHeight. Basically it get clientHeight and then add with paddingTop and paddingBottom (if any) to get offsetHeight value. By definition offsetHeight = clientHeight+paddingTop+paddingBottom.
I'm using clientHeight because sometimes the offsetHeight always get 0 value, but clientHeight will always have value (as far as I know).
function getOffsetHeight(el) {
var hh = 0;
if (el) {
hh = el.clientHeight;
if (el.style.paddingTop != "") {
hh += parseInt(el.style.paddingTop);
}
if (el.style.paddingBottom != "") {
hh += parseInt(el.style.paddingBottom);
}
}
return hh;
}