let height = document.getElementById('d').clientHeight
console.log(height);
img{
height:100%;}
<div id = 'd'>
<img src="https://via.placeholder.com/100x150">
</div>
let height = document.getElementById('d').clientHeight
console.log(height);
img{
height:100%;}
<div id = 'd'>
<img src="https://via.placeholder.com/100x150">
</div>
The image hasn't loaded when you are console logging. You can create an event listener that waits for the image to be loaded and then it will show the proper height.
function loaded() {
let height = document.getElementById('d').clientHeight;
console.log(height);
}
const img = document.getElementById('img');
if (img.complete) {
loaded()
} else {
img.addEventListener('load', loaded)
}
img{
height:100%;}
<div id = 'd'>
<img id='img' src="https://via.placeholder.com/100x150">
</div>
Because the image hasn't loaded when your code is executing:
setTimeout(() => {
let height = document.getElementById('d').clientHeight
console.log(height);
}, 1000)
<div id = 'd'>
<img src="https://via.placeholder.com/100x150">
</div>
If your code depends on knowing the height of the image in order to run correctly, you need to check whether the image is loaded, and wait until it has if it hasn't yet.
The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.
addEventListener('load',(event)=>{
let height = document.getElementById('d').clientHeight
console.log(height);
});