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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.