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

Asked

Viewed 168 times

1

Assuming I have 10 img elements on my page. I would then like to create an array that contains the attr-src of each img contained on that page. How do I perform such a task?

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' ]

0

You can do it like this:

var urls = $('img').map(function(){
    return $(this).attr('src');
});

If you need the array in native format join .get(); at 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 the .map(). They are similar and transform one array into another, replacing each element of the array with what is returned in the return.

#2

If you use return img.src; you will receive the full url. If you use return img.getAttribute('src'); you will receive what is in HTML, without being transformed into full url.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.