JavaScript - get all SVG images from web page
In this article, we would like to show you how to get all SVG images from web page using JavaScript.
Quick solution:
document.querySelectorAll('svg');
or:
document.querySelectorAll('img[src$=".svg"]');
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.
1. Embeded <svg> elements
In this example, we create a function that uses querySelectorAll() method with 'svg' selector to get all svg elements on 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>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="height:100px;">
<path d="M505 442.7 405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path>
</svg>
<script>
function getSvg() {
return document.querySelectorAll('svg');
}
// Usage example:
window.addEventListener('load', function() {
console.log([...getSvg()]);
});
</script>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="height:100px;">
<path d="M505 442.7 405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path>
</svg>
</body>
</html>
2. Images with .svg extension
In this example, we create function that uses querySelectorAll() method with 'img[src$=".svg"]' selector to get all the <img> elements with .svg 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/1632934722_loupe.svg" />
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
<script>
function getSvg() {
return document.querySelectorAll('img[src$=".svg"]');
}
// Usage example:
window.addEventListener('load', function() {
var svgImages = getSvg(); // gets all SVG images
for(var i = 0; i < svgImages.length; ++i) {
console.log(svgImages[i].src); // prints image src in the console
}
});
</script>
<img src="https://dirask.com/static/bucket/1632934722_loupe.svg" />
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
</body>
</html>
Note:
As you can see, the method gets only images with
.svgextension, omitting.pngimages.