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?
4 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();
7 Comments
Raptor
variable
images is an array of DOMElement named img, i.e. <img> tag. Need to further extract the src attribute.ThiefMaster
Ah, didn't notice him asking about the src values. Answer updated.
Gabo Esquivel
another for loop syntax
for(var i in images ){ srcList.push(images[i].src); }RobG
@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.
|
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
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
RobG
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) ;-)