EN
JavaScript - get src of all images on web page
0 points
In this article, we would like to show you how to get src of all images on web page using JavaScript.
Quick solution:
xxxxxxxxxx
1
const findImages = () => {
2
const urls = [];
3
for (const image of document.images) {
4
urls.push(image.src);
5
}
6
return urls;
7
};
or:
xxxxxxxxxx
1
const findImages = () => {
2
const images = document.querySelectorAll('img');
3
const urls = [];
4
for (const image of images) {
5
urls.push(image.src);
6
}
7
return urls;
8
}
In this example, we use document.images
property to get a collection of the images in the current HTML document. Then we iterate the collection using for...of
loop to get src
of all images.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<!-- Image 1: dirask logo -->
5
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
6
<script>
7
8
var images = document.images;
9
10
function findImages() {
11
var urls = [];
12
for (var i = 0; i < images.length; ++i) {
13
urls.push(images[i].src);
14
}
15
return urls;
16
}
17
18
19
// Usage example:
20
21
window.addEventListener('load', function() {
22
console.log(findImages());
23
});
24
25
</script>
26
<!-- Image 2: JavaScript logo -->
27
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
28
</body>
29
</html>
In this example, we use querySelectorAll()
method to get the collection of all images on the web page. Then using for loop we create array of src
properties of all images.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<!-- Image 1: dirask logo -->
5
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
6
<script>
7
8
function findImages() {
9
var images = document.querySelectorAll('img');
10
var urls = [];
11
for (var i = 0; i < images.length; ++i) {
12
urls.push(images[i].src);
13
}
14
return urls;
15
}
16
17
18
// Usage example:
19
20
window.addEventListener('load', function() {
21
console.log(findImages());
22
});
23
24
</script>
25
<!-- Image 2: JavaScript logo -->
26
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
27
</body>
28
</html>
Note:
The
findImages()
function needs to be executed after windowload
event or at the end of the script to make sure that all items are loaded before the function execution.