EN
JavaScript - get all png images from web page
0 points
In this article, we would like to show you how to get all .png
images from web page using JavaScript.
Quick solution:
xxxxxxxxxx
1
document.querySelectorAll('img[src$=".png"]');
Note:
In both cases the code needs to be executed after window
load
event or at the end of the script to make sure that all elements are loaded before the function execution.
In this example, we create function that uses querySelectorAll()
method with 'img[src$=".png"]'
selector to get all the <img>
elements with .png
extension from the web page. Then we call the function on window load
event.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
img {
7
width: 100px;
8
height: 100px;
9
}
10
11
</style>
12
</head>
13
<body>
14
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
15
<img src="https://dirask.com/static/bucket/1632934722_loupe.svg" />
16
<script>
17
18
function getPng() {
19
return document.querySelectorAll('img[src$=".png"]');
20
}
21
22
23
// Usage example:
24
25
window.addEventListener('load', function() {
26
var pngImages = getPng(); // gets all png images
27
for(var i = 0; i < pngImages.length; ++i) {
28
console.log(pngImages[i].src); // print image src in the console
29
}
30
});
31
32
</script>
33
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
34
<img src="https://dirask.com/static/bucket/1632934722_loupe.svg" />
35
</body>
36
</html>
Note:
As you can see, the method gets only images with
.png
extension, omitting other images.