Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Get each image src

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?

like image 203
MeltingDog Avatar asked Feb 25 '13 05:02

MeltingDog


People also ask

How to get all image src in jQuery?

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

How to get img jQuery?

To get the source of an image, we can use jQuery to get the img src using the attr() method. The jQuery attr method will return the location of the file as a string.

How add src attribute in jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.


2 Answers

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

  $(".photo").each(function() {  
   imgsrc = this.src;
   console.log(imgsrc);
  });  
like image 51
EnterJQ Avatar answered Oct 04 '22 16:10

EnterJQ


$(document).ready(function(){
  $(".photo").each(function() {  
       imgsrc = this.src;
       console.log(imgsrc);
  });    
});
like image 42
coolguy Avatar answered Oct 04 '22 15:10

coolguy