0

I can't get the dimensions of image. Here is the code...

The HTML:

<img class="edit-img about-img" src="images/box-model.jpg">

The JavaScript:

function getDimension () {
    var img = document.getElementsByClassName('about-img');

    var width = img.clientWidth;
    var height = img.clientHeight;
}

window.onload = getDimension;

It say's that the variable 'width' & 'height' is undefined. I also tried using img.width & img.height.

Soumya
  • 147
  • 9

3 Answers3

5

getElementsByClassName() does just that - get elements by class name.

It doesn't return a single Node - even if there is only one element with that class name - but rather a NodeList of all the elements.

What you'd be looking for is something like this:

var img = document.getElementsByClassName('about-img')[0];

var width = img.clientWidth;
var height = img.clientHeight;

However, hard-coding the index like this assumes that there is only one image with that class name. That may not always be true, and if it isn't, then just taking the first element probably won't get you what you're looking for. In this case, I would give the image an ID:

<img class="edit-img about-img" id="my-image" src="images/box-model.jpg">

After you've done this, you can use getElementById(), which works as you expected getElementsByClassName() to:

var img = document.getElementById('my-image');

var width = img.clientWidth;
var height = img.clientHeight;
AstroCB
  • 12,337
  • 20
  • 57
  • 73
1

Select the element by it's id attribute, to get the image you are referring to.

function getDimension () {
    var img = document.getElementById('myId');
    var width = img.clientWidth;
    var height = img.clientHeight;
    console.log(width);
    console.log(height);
}

window.onload = getDimension();
<img id="myId" class="edit-img about-img" src="http://via.placeholder.com/350x150">
Chava Geldzahler
  • 3,605
  • 1
  • 18
  • 32
1

Fiddle example

function getDimension () {
    var img = document.getElementById('imageId');
    var width = img.clientWidth;
    var height = img.clientHeight;
    alert(width);
}

window.onload = getDimension();

Just have to use an ID instead of class name in your JavaScript. Check the fiddle.

KidBilly
  • 3,408
  • 1
  • 26
  • 40