Tutorial :Get href,src,width,height of image using jQuery


I want to get the href, src, width, height of all images on a page. The jQuery code is

$('img:regex(data:extension, jpg)').each(function() {      var imgsrc = $(this).attr('href');     //$(this).attr('width') =0;                                         var newImg = new Image();  newImg.src = imgsrc;      var width = newImg.width;  //width is 0;      });  

Not sure what is wrong, any ideas?

Thanks Jean


Well IMG tags use 'src' not 'href'.


This example works for your problem.

$("img").each(function(){      alert($(this).attr('src') + " - " + $(this).attr('width') + " - " + $(this).attr('height'));  });  


I wouldn't be surprised if this doesn't work -- at least, not until the document and all of its resources are completely loaded. HTML doesn't normally specify the width or height of an image unless it's been specified in the tag itself.

So you'd have to at least wait for the onload event.

The other solution, which could prove to be a bit of a pain, is to check the rendered width/height of the image on the server side and provide that in the <img width, height> attributes.


Assuming that you have this markup:

<a href="link1"><img src="foo.jpg"></a>  <a href="link2"><img src="bar.jpg"></a>  

You can obtain the wrapping link by jQuery.closest() as follows:

$('img[src$=.jpg]').each(function() {      $img = $(this);      $link = $img.closest('a');      var href = $link.attr('href');      // ...        // Assuming you want the image's client width/height:      var width = $img.width();      var height = $img.height();      // ...  });  

The [name$=value] is by the way the attribute-ends-with selector.


$('img').each(function() {     var imgwidth  = $(this)[0].offsetWidth;     var imgheight = $(this)[0].offsetHeight;      console.log(imgwidth ,' X ' , imgheight);  });  

I think this should help


In regards to the above answer from Rei...that's correct, you really want to be sure everything has completely loaded first before you start grabbing dimensions. A helpful tool for this is jquery.imagesloaded .

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »