Assuming I have 10 img elements on my page. I would like to create an array that has as content the attr-src of each img contained in that same page. How do I accomplish this task?
Assuming I have 10 img elements on my page. I would like to create an array that has as content the attr-src of each img contained in that same page. How do I accomplish this task?
Considering:
<img src="image1" />
<img src="image2" />
<img src="image3" />
Using pure javascript:
var
srcs = [],
images = document.querySelectorAll('img'),
imagesLength = images.length,
index = 0;
for ( index; index < imagesLength; index++ )
{
srcs[ index ] = images[ index ].src;
}
console.log( srcs ); // [ 'image1', 'image2', 'image3' ]
Using Jquery:
var
srcs = [],
images = $('img');
images.each( function ( index )
{
srcs[ index ] = $( this ).attr('src')
} );
console.log( srcs ); // [ 'image1', 'image2', 'image3' ]
You can do this:
var urls = $('img').map(function(){
return $(this).attr('src');
});
If you need the array in native format joins .get();
to the end.
You can do this in JavaScript too, without jQuery:
var imagens = document.getElementsByTagName('img');
var urls = [].map.call(imagens, function(img){
return img.src;
});
Whether in jQuery or native JavaScript, the semantically correct method is .map()
. They are similar and transform an array into another, replacing each element of the array with what is returned in return
.
If you use return img.src;
you will receive the full url. If you use return img.getAttribute('src');
you will get what is in the HTML, without being transformed into a full url.