Skip to content

Count list items in data before outputting to HTML

I have a list that is being returned using ajax that looks like this…


<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>

I am inserting it into a HTML element like this…


This is working correctly, but I would like to count the number of list items before I output it to the element. I have tried the following but it just gives me the count of characters…


Where am I going wrong? Is there a way to do this before outputting the HTML?



Your data is just a string, so you can use jQuery to turn it into jquery object and then select li elements from that object and get the length.

const data = '<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>'
const html = $(data);


<script src=""></script>
<div id="output"></div>
User contributions licensed under: CC BY-SA
5 People found this is helpful