JQuery get img source attributes from list and click on array

I have a list of thumbnails and would like to insert 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> 
+21
jquery arrays push loops attributes
Mar 01 '10 at 10:08
source share
2 answers

You can create an 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, not a strict Javascript array, but it will act like an array. For example, this is a legal code:

 for (int i=0; i<tn_array.length; i++) { alert(tn_array[i]); } 

However, you can call get() , which will make it a strict array:

 var tn_array = $("#thumbnails img").map(function() { return $(this).attr("src"); }).get(); 

How do you say the difference? Call:

 alert(obj.constructor.toString()); 

The first version will be:

 function Object() { [native code] } 

Second:

 function Array() { [native code] } 
+48
Mar 01 '10 at 10:11
source share

You can loop through the img element:

 var tn_array = Array(); $('#thumbnails img').each(function() { tn_array.push($(this).attr('src')); }); 
+5
Mar 01 '10 at 10:13
source share



All Articles