jQuery get img source attributes from list and push into array
36,764
Solution 1
You can create the array of src attributes more directly using map()
:
var tn_array = $("#thumbnails img").map(function() {
return $(this).attr("src");
});
Edit: tn_array
is an object here rather than a strict Javascript array but it will act as an array. For example, this is legal code:
for (int i=0; i<tn_array.length; i++) {
alert(tn_array[i]);
}
You can however call get()
, which will make it a strict array:
var tn_array = $("#thumbnails img").map(function() {
return $(this).attr("src");
}).get();
How do you tell the difference? Call:
alert(obj.constructor.toString());
The first version will be:
function Object() { [native code] }
The second:
function Array() { [native code] }
Solution 2
You can loop through ever img
element:
var tn_array = Array();
$('#thumbnails img').each(function() {
tn_array.push($(this).attr('src'));
});
Author by
FFish
Updated on July 09, 2022Comments
-
FFish almost 2 years
I have this thumbnail list and would like push the image paths (sources) into an array: tn_array
<ul id="thumbnails"> <li><img src="somepath/tn/004.jpg" alt="fourth caption" /></a></li> <li><img src="somepath/tn/005.jpg" alt="fifth caption" /></a></li> <li><img src="somepath/tn/006.jpg" alt="sixth caption" /></a></li> </ul>
-
harpo about 14 yearsYes, thanks +1. I was looking for a similar technique to get an array of val(). Kind of surprising jquery doesn't have something built in for this. Seems like a quibble, but it is, after all, the "write less" library. :)
-
harpo about 14 yearsAlso remember that if you want an actual array, you need to call .get() on the result of .map().