Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get img source attributes from list and push into array

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>
like image 325
FFish Avatar asked Mar 01 '10 10:03

FFish


2 Answers

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] }
like image 187
cletus Avatar answered Oct 05 '22 19:10

cletus


You can loop through ever img element:

var tn_array = Array();

$('#thumbnails img').each(function() {
    tn_array.push($(this).attr('src'));
});
like image 39
Felix Kling Avatar answered Oct 05 '22 20:10

Felix Kling