In this tutorial we will learn how to Count number of images on web page with JavaScript. For this we can use onclick attribute, .getElementsByTagName() method, .length property and .innerHTML property.
Table of Contents
HTML Code
HTML Code is given below, we have a button tag with onclick event to trigger the JavaScript function and three images.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Count number of images on website with JavaScript</title>
<style>
img{max-width: 50px;}
</style>
</head>
<body>
<p>Total Images: <span id="count"></span></p>
<img src="html.png">
<img src="css.png">
<img src="js.png">
<br>
<button onclick="countImages()">Count Images</button>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code given below.
<script>
function countImages(){
var images = document.getElementsByTagName('IMG');
var count = images.length;
document.getElementById('count').innerHTML=count;
}
</script>
On button click, JavaScript function will first select all the images using .getElementsByTagName() method. Then all images are counted using .length property.
This count is then displayed using .innerHTML property.
Demo
There are ___ images on this page.
Video Tutorial
Watch video tutorial on how to count number of images on page using JavaScript.