Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function to get all images in html

Tags:

javascript

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?

like image 292
adit Avatar asked Feb 17 '12 01:02

adit


People also ask

What is image () in JavaScript?

Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .

Which property is used to return all IMG elements?

The images property returns a collection of all <img> elements in a document.


2 Answers

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();
like image 192
ThiefMaster Avatar answered Sep 21 '22 10:09

ThiefMaster


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);
like image 23
RobG Avatar answered Sep 19 '22 10:09

RobG