I am looking to get the height and width defined within the tag, not the original or actual height displayed on the page.
For example
<img id="testImg" src="http://test.com/img.png" height="300" width="250">
I would expect to return a height of 300 and width of 250.
In the example where the height and width are not defined within the tag:
<img id="testImg" src="http://test.com/img.png">
I would expect to return false or undefined or 0 for both the height and width.
With the JavaScript:
var img = document.getElementById("testImg");
console.log(img.naturalHeight);
console.log(img.height);
img.naturalHeight and img.height do not return what is defined within the tag. These return the original or actual image height.
2
Answers
Consider using
getAttribute()
to retrieve attribute values from an element:To get the height and width of an
<img>
tag using plain JavaScript, you can use theheight
andwidth
properties of theHTMLImageElement
object. Here’s an example: