What is the difference between jQuery.size() and jQuery.length?


jQuery.size() method

This method returns the number of elements in the object. The size() method deprecated in jQuery 1.8 and completely removed in jQuery 3.0. As an alternative, the length property is used.

Example

You can try to run the following code to learn how to work with size() method.
Note: To run the jQuery size() method, use jQuery version less than 1.8, since it deprecated in jQuery 1.8. Generally, the length property is preferred now.

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".btn").click(function(){
        alert($("li").size());
    });
});
</script>
</head>
<body>

<button class="btn">How many li elements?</button>

<ol>
  <li>India</li>
  <li>US</li>
  <li>UK</li>
  <li>Australia</li>
</ol>

</body>
</html>

jQuery length

The length property shows the number of elements in the jQuery object. Length does the same work of the size() method and avoids the overhead of a function call.

Example

You can try to run the following code to learn how to work with jQuery length property:

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".btn").click(function(){
        alert($("li").length);
    });
});
</script>
</head>
<body>

<button class="btn">How many li elements?</button>

<ol>
  <li>India</li>
  <li>US</li>
  <li>UK</li>
  <li>Australia</li>
</ol>

</body>
</html>

Updated on: 12-Dec-2019

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements