2

I have the following image tag

<img class="someclass" src="somesrc" width="220" height="165" />

The browser is displaying the image with its original width and height which is 480x360

I want to get the image width and height attributes from the image tag which should return 220 and 165

I have tried the following

var img = document.getElementsByClassName('someclass');
console.log(img.clientWidth);
console.log($('.someclass').attr('width'));

But it returns me undefined.

The following code returns me the actual width and height of the image. which is 480

$('.someclass').width();

Is there any way that it should return the 220 and 165?

Ahmad
  • 2,099
  • 10
  • 42
  • 79

3 Answers3

3

You need to get the width attribute of a single element not a nodeList as you were returning.

Try this...

var element = document.querySelector('.someclass');
console.log(element.getAttribute('width')); //220
console.log(element.getAttribute('height')); //165
curv
  • 3,796
  • 4
  • 33
  • 48
0

Thanks to all for your help. But I have found the solution. The following code works for me.

$('img.someclass).load(function(){
  var width = $(this).attr('width');
  var height = $(this).attr('height');
  if(width != 'undefined') {
     $(this).css('width', width);
  }
  if(height != 'undefined') {
    $(this).css('height', height);
  }
});
Ahmad
  • 2,099
  • 10
  • 42
  • 79
-2

Try

var img = document.getElementsByClassName('someclass')[0];
var width = img.width;
var height = img.height

and in case you want to set new values just do:

img.width = yourvalue;
img.height = yourvalue;

it works fine, so plz don't downvote people for no reason

Antonis
  • 647
  • 6
  • 15
  • You misread the question he is after the attribute value not the rendered width / height – curv Nov 28 '16 at 15:06