Jquery: Get each image src

37,216

Solution 1

If you have given same class name for all img tag then try this ,

  $(".photo").each(function() {  
   imgsrc = this.src;
   console.log(imgsrc);
  });  

Solution 2

$(document).ready(function(){
  $(".photo").each(function() {  
       imgsrc = this.src;
       console.log(imgsrc);
  });    
});

Solution 3

May be you are missing doc ready handler:

$(function(){
  $.each($(".photo"), function() {
    var imgsrc = $(this).attr("src").length;
    console.log(imgsrc); // logging length it should now print the length
  });
});

make sure to load this script first then your $.each() function:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Share:
37,216
MeltingDog
Author by

MeltingDog

Updated on July 12, 2022

Comments

  • MeltingDog
    MeltingDog almost 2 years

    I have a series of images each with the class "photo";

    I want to go through each of these and retrieve the photo source, for use later in an if statement. I have written the below code to do this, but have not been successful:

    $.each($(".photo"), function() {
      var imgsrc = $(this).attr("src").length;
      console.log(imgsrc);
    });
    

    I am not sure where I have gone wrong here. It seems to make sense to me, but I dont get anything in the console.

    Can anyone point me in the right direction?

  • MeltingDog
    MeltingDog about 11 years
    surely that would still work though? It would just give me a number instead of a string. I have length there because I want to make and if statement later on eg: if(imgsrc < 1)
  • yoda
    yoda about 11 years
    you can still make that statement, if (imgsrc == undefined), see updated answer
  • Alexander Kim
    Alexander Kim over 10 years
    Why we can't use imgsrc = this.attr('src')? it throws me an error
  • Jigar Bhatt
    Jigar Bhatt over 9 years
    Many Many thanx bro, this answer is very useful for me. :)