Ordered HTML 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. So, we need to count all the items to show it to the user. 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 handle of the list you want to count and then walk through the nodes (i.e. list 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: And now place the following code at the place where you want to display the count. SEE ALSO: Randomize the items in an HTML list Make sure that you replace ‘my-html-list’ with the id of your list. You can have any ID for your list. Also, please note, that you can use this function on ordered lists :-) It works on all both types of lists because both the lists contain LI items. I hope this piece of code was useful for you. Do let me know if you have any problem with it. Thank you for using TechWelkin. I tried paste the provided example: function countItems(listID){ var ul = document.getElementById(listID); var i=0, itemCount =0; while(ul.getElementsByTagName(‘li’) [i++]) itemCount++; document.write(itemCount); } in the HEAD section of my page; and countItems(‘my-html-list’) at the place where I want to display the count. Surprising, there is no display of the count except only when I paste all the script after the unordered list in the page, then it is seen. Had tried on microsoft edge and google chrome with the same result. :( Also I tried to replace the output code of document.write with document.getElementById(‘txt’).innerHTML, surprisingly there is no output at my as it seems only document.write works. :( Was hoping can really display the count at any place, lol Thank you Comgreen Comment * Name * Email * Website
Δ