- 1). Create an HMTL file in an text editor or in Notepad. Create a <div> tag with an "id" attribute and place <img> tags inside the <div> tag. For example, type
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Count Images</title>
</head>
<body>
<div><img src="http://example.com/image1.jpg" alt="image1" /><img src="http://example.com/image2.jpg" alt="image2" /><img src="http://example.com/image3.jpg" alt="image3" /></div>
</body>
</html> - 2). Create a JavaScript function and place it between the <head> tags. Get the contents of the <div> tag and store it in a variable. For example, type
<script type="text/javascript">
function countImages() {
var divContents = document.getElementById("images").innerHTML; - 3). Use a regular expression to get array elements that match the opening of the <img> tag. For example, type
var matches = divContents.match(/<img/); - 4). Get the number of images by referencing the number of elements in the array. For example, type
var numMatches = matches.length;
alert("Number of matches is " + numMatches);
}
</script> - 5). Call the JavaScript function right before the closing <body> tag to give the HTML page time to load. For example, type:
<script type="text/javascript">
countImages();
</script>
SHARE