Hi guys, sometimes we may need to count the number of elements under a particular element. jQuery helps us to find the number of elements very easily, consider the following HTML
<ul id="list"> <li>1</li> <li>2</li> <li>3</li> </ul>
we can use the following code to find out the number of list items under the UL
var count = $('#list').size() //here the value in count will be 3
If you want to find out the number of elements of all types under a particular elelment, then you can use *
<div id="first"> <span>Span element 1</span> <span>Span element 2</span> <p>paragraph</p> <span>Another span</span> <div>another div</div> </div>
If you want to find out the total number of ‘span’ elements under the div with id “first”, use the following code
var count = $("#first > span ").size() //value in the var 'count' will be 3
we can use the following code to get the number of elements of all types under the div with id “first”
var count = $("#first > *").size() //value in the var count will be 5