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 length property.

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, and length is the number of selected elements.

Read jQuery Selectors.


Learn more about the similar topics:
Tutorials
jQuery Selectors
jQuery Traversing: Ancestors
jQuery Traversing: Descendants
jQuery Traversing: Siblings
jQuery Traversing: Filtering
Exercises & Assignments
Write jQuery code to count the items of a list
Write jQuery code to find the total of a table column
Write jQuery code to add alternate row colors to a table
Interview Questions & Answers
What are jQuery selectors?
What is the difference between find() and children() in jQuery?
What is the difference between parent(), parents() and closest() in jQuery?
How do you check if an element exists in jQuery?
What is the difference between this and $(this) in jQuery?
What is the use of end() in jQuery?