Count list items in data before outputting to HTML

Tags: ,



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

console.log(data);

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

I am inserting it into a HTML element like this…

$("#output").html(data);

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…

console.log(data.length);

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

Answer

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);

console.log(html.find('li').length)

$("#output").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>


Source: stackoverflow