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:
document.querySelectorAll('img[src$=".png"]');
Note:
In both cases the code needs to be executed after window
loadevent or at the end of the script to make sure that all elements are loaded before the function execution.
Practical example
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.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
img {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
<img src="https://dirask.com/static/bucket/1632934722_loupe.svg" />
<script>
function getPng() {
return document.querySelectorAll('img[src$=".png"]');
}
// Usage example:
window.addEventListener('load', function() {
var pngImages = getPng(); // gets all png images
for(var i = 0; i < pngImages.length; ++i) {
console.log(pngImages[i].src); // print image src in the console
}
});
</script>
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
<img src="https://dirask.com/static/bucket/1632934722_loupe.svg" />
</body>
</html>
Note:
As you can see, the method gets only images with
.pngextension, omitting other images.