Javascript function to get all images in html

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

+7
source share
4 answers

You can easily get an array containing all img elements through 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 can also use the document.images collection.


If you use 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(); 
+21
source

There is a collection of document.images , 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; } 

Change update for ECMAScript ES5

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

If you have ES6 arrow functions:

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

You can use jQuery to search all image tags. JQuery code will look like this:

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

I understand that this is old, but just wanted to add that you can highlight it:

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

I am not sure about cross browser support.

0
source

All Articles