Write jQuery code to count the items of a list
Description: Count the items of the list and show “Total items: N” in the paragraph.
Hint:
- A jQuery object has a
lengthproperty.
HTML of the page
<ul id="fruits">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
<li>Orange</li>
</ul>
<p id="count"></p>
Solution
var total = $('#fruits li').length;
$('#count').text('Total items: ' + total);
HTML after the code runs
<p id="count">Total items: 4</p>
How it works
$('#fruits li')selects all list items, andlengthis the number of selected elements.
Read jQuery Selectors.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |