Languages
[Edit]
EN

JavaScript - get all png images from web page

0 points
Created by:
Jan-Alfaro
711

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 load event 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 .png extension, omitting other images.

 

References

  1. Document.querySelectorAll() - Web APIs | MDN
  2. Window: load event - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join