EN
JavaScript - find all images on web page
0 points
In this article, we would like to show you how to find all images on web page using JavaScript.
Quick solution:
xxxxxxxxxx
1
var images = document.images;
or:
xxxxxxxxxx
1
document.querySelectorAll('img');
In this example, we use document.images
property that contains a collection of the images in the current HTML document.
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; // contains all images
9
10
11
// Usage example:
12
13
window.addEventListener('load', function() {
14
console.log([images]);
15
});
16
17
</script>
18
<!-- Image 2: JavaScript logo -->
19
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
20
</body>
21
</html>
In this example, we use querySelectorAll()
method to get the collection of all images on the web page.
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
return document.querySelectorAll('img'); // finds all images
10
}
11
12
13
// Usage example:
14
15
window.addEventListener('load', function() {
16
console.log([findImages()]);
17
});
18
19
</script>
20
<!-- Image 2: JavaScript logo -->
21
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
22
</body>
23
</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.