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:
var images = document.images;
or:
document.querySelectorAll('img');
Practical examples
1. Using document.images
property
In this example, we use document.images
property that contains a collection of the images in the current HTML document.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<!-- Image 1: dirask logo -->
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
<script>
var images = document.images; // contains all images
// Usage example:
window.addEventListener('load', function() {
console.log([...images]);
});
</script>
<!-- Image 2: JavaScript logo -->
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
</body>
</html>
2. Using querySelectorAll()
method
In this example, we use querySelectorAll()
method to get the collection of all images on the web page.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<!-- Image 1: dirask logo -->
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
<script>
function findImages() {
return document.querySelectorAll('img'); // finds all images
}
// Usage example:
window.addEventListener('load', function() {
console.log([...findImages()]);
});
</script>
<!-- Image 2: JavaScript logo -->
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
</body>
</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.