JavaScript: Count Items in HTML List

Get the JavaScript code for counting items in an OL or UL list and then display the count wherever you want on your web page.

The other day I needed to dynamically count the total number of items in an HTML unordered list. The ordered list (created with OL tag) are by default counted as each item is preceded by its number in the list. But the lists created using UL tag are not numbered.

If you are displaying this count of unordered list items on your page –you may not want to update the count every time you update the list. So, a dynamic solution is preferred in such a situation. With the help of JavaScript you can perform this task very easily.

The logic is simple. What we basically do is to get the handle of the list you want to count and then loop through the items while incrementing a counter. When the loop is done, counter variable would contain the total number of items. Then you can print this count wherever you want on your web page.

Paste the following JavaScript code in the HEAD section of your page

<script type='text/javascript'>
function countItems(listID){
var ul = document.getElementById(listID);
var i=0, itemCount =0;
while(ul.getElementsByTagName('li') [i++]) itemCount++;

And now place the following code at the place where you want to display the count.

<script> countItems(‘my-list’)</script>

SEE ALSO: Randomize the items in an HTML list

Note 1: Replace ‘my-list’ with the id of your list.
Note 2: It’s not that you can’t use this function on ordered lists! You can.

Leave a Reply

Your email address will not be published. Required fields are marked *