skip to Main Content

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


  1. Consider using getAttribute() to retrieve attribute values from an element:

    var img = document.getElementById('testImg');
    console.log(img.getAttribute('height'));
    console.log(img.getAttribute('width'));
    
    var img0 = document.getElementById('testImg0');
    console.log(img0.getAttribute('height'));
    console.log(img0.getAttribute('width'));
    <img id="testImg" src="http://test.com/img.png" height="300" width="250">
    <img id="testImg0" src="http://test.com/img.png">
    Login or Signup to reply.
  2. To get the height and width of an <img> tag using plain JavaScript, you can use the height and width properties of the HTMLImageElement object. Here’s an example:

    <script>
        var imgElement = document.getElementById('myImage');
    
        // Get the height and width
        var height = imgElement.height;
        var width = imgElement.width;
    
        // Log the values
        console.log('Height:', height);
        console.log('Width:', width);
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search