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?
Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .
The images property returns a collection of all <img> elements in a document.
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();
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;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With