I have a list that is being returned using ajax that looks like this…
JavaScript
x
4
1
console.log(data);
2
3
<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>
4
I am inserting it into a HTML element like this…
JavaScript
1
2
1
$("#output").html(data);
2
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…
JavaScript
1
2
1
console.log(data.length);
2
Where am I going wrong? Is there a way to do this before outputting the HTML?
Advertisement
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.
JavaScript
1
6
1
const data = '<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>'
2
const html = $(data);
3
4
console.log(html.find('li').length)
5
6
$("#output").html(html);
JavaScript
1
2
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id="output"></div>