16

I wanted to have a javascript function to basically return an array of all the img src there is in a page, how do I do this?

1
  • 3
    What did you try? Show the code you've written so far. Commented Feb 17, 2012 at 2:29

4 Answers 4

49

You can easily get an array containing all img elements via document.getElementsByTagName():

var images = document.getElementsByTagName('img'); 
var srcList = [];
for(var i = 0; i < images.length; i++) {
    srcList.push(images[i].src);
}

Instead of document.getElementsByTagName('img') you could also use the document.images collection.


If you are using jQuery, you can also use $('img') which gives you a jQuery object containing all img elements.

var srcList = $('img').map(function() {
    return this.src;
}).get();
Sign up to request clarification or add additional context in comments.

7 Comments

variable images is an array of DOMElement named img, i.e. <img> tag. Need to further extract the src attribute.
Ah, didn't notice him asking about the src values. Answer updated.
another for loop syntax for(var i in images ){ srcList.push(images[i].src); }
@GaboEsquivel: That's enumeration syntax, which shouldn't be used when you want to iterate indices.
@ShivanRaptor—document.images is an HTMLCollection, not an array. The only similarities they have is that they both have members that can be accessed by numeric index and a special length property.
|
14

There is a document.images collection, so:

function allSrc() {
  var src = [];
  var imgs = document.images;
  for (var i=0, iLen=imgs.length; i<iLen; i++) {
    src[i] = imgs[i].src;
  }
  return src;
}

Edit Update for ECMAScript ES5

Array.prototype.map.call(document.images,function(img){return img.src});

If you have ES6 arrow functions available:

Array.prototype.map.call(document.images, img => img.src);

Comments

0

You can use jQuery to find all of the image tags. The jQuery code will be as follows:

images = []
$('img').each(function(idx, img) {
    images.push(img.src)
});

Comments

0

I understand this is old however just wanted to add that you can one line it:

images = [].slice.apply(document.getElementsByTagName('img'), null);

I'm not sure of cross browser support.

1 Comment

If you replace document.getElementsByTagName('img') with document.images it will be 21 characters shorter and faster. And if you use reduce you can return the actual src attribute values rather than the images (which is what the OP wants) ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.