JavaScript Count list items

In this tutorial we will learn how to Count list items with JavaScript. getElementsByTagName() method and length property can be used to get the total number of li tags inside a list or menu.

getElementsByTagName() method

getElementsByTagName() method returns all HTML elements with a specified tag name.

In this example getElementsByTagName() method is used to select all list items of a list.

length property

length property returns the length of string or total number of elements in an object.

In this example we have used length property to count all li tags.

HTML Code

HTML Code is given below, in this code we have a ul list with three list items and a button.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Count li tags</title>
</head>             
<body>
    
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul> 
<button onclick="countListItems()">Count List Items</button>    
    
<script src="script.js"></script>    
</body>
</html>

JavaScript Code

Take a look at the JavaScript code, In this code user defined function countListItems() will count total number of li tags or list items.

getElementsByTagName() method is used to select all li tags.

length property will return the total count.

<script>
function countListItems()
{
    var listItems = document.getElementsByTagName("LI");
    var totalListItems = listItems.length;
    alert(totalListItems);
}
</script>

Demo

Video Tutorial

Watch video tutorial on How To Count list items or li tags using JavaScript.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color