In this article, I will introduce a method to count the number of list (li) elements within a specified area on a page using jQuery’s .each() and display the count.
CSS Description to Display the Count of li Elements
Below is the CSS description for the output destination of the list (li) element count (.clTxt). Please modify it as needed.
<style type="text/css">
<!--
.cWrap{
width:900px;
margin:0 auto;
}
.clLiWrap{
width:220px;
margin:0 auto;
text-align:left;
}
.clTxt{
font-weight:bold;
padding:5px 0;
}
-->
</style>
JavaScript Description to Count li Elements Using jQuery’s .each() and Output the Count
This code counts the number of li elements using .each() and outputs the count to the element with class=”clTxt”.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript"><br />
<!--
$(function() {
var cnt=0;
$(".clLiWrap li").each(function() {
++cnt;
});
$(".clTxt").text("The number of list elements is "+cnt+".");
});
// -->
</script>
HTML Description to Display the Count of li Elements
Prepare the list (li) tags and the output destination (class=”clTxt”). Modify as needed.
<div class="clTxt"></div>
<div class="clLiWrap">
<ul>
<li><a href="https://dad-union.com/javascript/69">Switch multiple images using fade-in and fade-out with jQuery</a></li>
<li><a href="https://dad-union.com/javascript/63">Implement a fixed top and bottom bar on a smartphone site with iscroll.js</a></li>
<li><a href="https://dad-union.com/javascript/75">Expand and shrink image size on mouse over and out</a></li>
<li><a href="https://dad-union.com/javascript/60">Customize scrollbar with jquery.jscrollpane.min.js</a></li>
<li><a href="https://dad-union.com/javascript/57">Retrieve and display array information in JSON format with getJSON</a></li>
</ul>
</div>
<!--/clLiWrap-->
Page Demonstration of Counting and Displaying Tag Elements Using jQuery’s .each()
Page Demonstration of Counting and Displaying Tag Elements Using jQuery’s .each()
It seems possible to count not only list (li) tags but also other repeating tag elements.
Please use it at your own risk if you are reusing this code. Do not reuse the Google Analytics tag within the demo page tags.