jQuery Difference between length and size()

How to find the number of matching elements ?

In jQuery, either length property and size method can be used to get the number of elements.

length property

length property is used to get the number of matching elements./p>


size method

size method is also used to get the number of matching elements but it is deprecated as of jQuery 1.8.


Functionality is equivalent in both size method and length property but preferred and recommended to use length instead of size method and length does not have a function call overhead.

jQuery Example for length and size differences

      <title>The jQuery Example - length and size differences</title>

 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>	
      <script type = "text/javascript">
        function get_matching_elements_count() {
          var count = $("p:not(:first)").size();
          var count1 = $("p:not(:first)").length;
          var htmlcontent = "Mathing elements count using size method: "+
                             count + "\nMathing elements count using "+
                             "length property: " + count1;

<p>line 0</p>
<p>line 1</p>
<p>line 2</p>
<p>line 3</p>
<p>line 4</p>
<p>line 5</p>
<p>line 6</p>
<input type="button" value="Get Count" onclick="get_matching_elements_count();"/>
slice method output

Except first paragraph elements will be considered and returns count 6 for both length property and size method.

length property is recommended and preferred.

'+' can be used to split string into multiple lines.

Displays result for length property and size method when clicking on 'Get Count' button.

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter