Catch all the src contained in the document and transform into array in jquery

1

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?

    
asked by anonymous 29.08.2015 / 08:15

2 answers

3

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' ]
    
29.08.2015 / 09:26
0

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;
});

Notes:

# 1

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 .

# 2

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.

    
29.08.2015 / 13:23