Getting the width and height of an Image

So I have a element and I want to get the image’s height and width property, however this is my css:

let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px',''));
let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px',''));
console.log(`width`,w);
console.log(`height`,h);
img#image{
    z-index: 0;
    display: block;
    top: 0px;
    margin-left: auto;
    margin-right: auto;

    max-height: 100%;
    max-width: 100%;

    position: absolute;
    align-self: center;

    margin: auto;
    left: 0;
    right: 0;
}
<img src="src.jpg" id="image">

as you can see i didn’t set a height and width property because I don’t want the image to have a fixed width and height, so someone introduced me to use:

window.getComputedStyle(document.getElementById('image')).getPropertyValue('height')

and so I did, but it is not accurate from my experience:

JS:

let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px',''))
let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px',''))
console.log(`width`,w)
console.log(`height`,h)

here is the screenshot of the results it logged:
https://media.discordapp.net/attachments/244238416248569857/812200556403490847/Screenshot_1540.png?width=1067&height=600

and here is the screenshot of the actual width and height of the element:
https://media.discordapp.net/attachments/244238416248569857/812200556000313354/Screenshot_1541.png?width=1067&height=600

as you can see the image is 670 x 514 but it logged 459 as its height, anyone can help me with this problem?

128 thoughts on “Getting the width and height of an Image”

  1. great post, very informative. I’m wondering why the other experts of this sector don’t understand this. You should proceed your writing. I’m confident, you’ve a great readers’ base already!|

    Reply