Reputation: 15488
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?
Upvotes: 12
Views: 41429
Reputation: 74738
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>
Upvotes: 1
Reputation: 10981
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 */ }
Upvotes: 0
Reputation: 1014
If you have given same class name for all img tag then try this ,
$(".photo").each(function() {
imgsrc = this.src;
console.log(imgsrc);
});
Upvotes: 24
Reputation: 7954
$(document).ready(function(){
$(".photo").each(function() {
imgsrc = this.src;
console.log(imgsrc);
});
});
Upvotes: 4