12

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?

3
  • just avoid the length you are good to go Commented Feb 25, 2013 at 5:47
  • @ubercooluk thanks but its seems to make no difference whether I use it or not Commented Feb 25, 2013 at 5:48
  • .photo is the class of the image..can you doublecheck that Commented Feb 25, 2013 at 5:49

4 Answers 4

24

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

  $(".photo").each(function() {  
   imgsrc = this.src;
   console.log(imgsrc);
  });  
Sign up to request clarification or add additional context in comments.

2 Comments

Why we can't use imgsrc = this.attr('src')? it throws me an error
this.attr('src') doesn't work because "this" isn't jQuerified yet: to fix that, do $(this).attr('src)
4
$(document).ready(function(){
  $(".photo").each(function() {  
       imgsrc = this.src;
       console.log(imgsrc);
  });    
});

Comments

1

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>

Comments

0

You are trying to read the lenght of an object / array out of context here :

var imgsrc = $(this).attr("src").length;

change to

var imgsrc = $(this).attr("src");

edit : in order to check if the attribute exists

if (imgsrc == undefined) { /* do something */ }

2 Comments

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)
you can still make that statement, if (imgsrc == undefined), see updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.