jQuery API

.size()

.size() Returns: Number

Description: Return the number of DOM elements matched by the jQuery object.

  • version added: 1.0.size()

<ul>
  <li>foo</li>
  <li>bar</li>
</ul>

We can determine the number of list items by calling .size():

alert('Size: ' + $('li').size());

This will alert the count of items:

Size: 2

The .length property is a slightly faster way to get this information.

Example:

Count the divs. Click to add more.

<!DOCTYPE html>
<html>
<head>
  <style>body { cursor:pointer; }
 div { width:50px; height:30px; margin:5px; float:left; background:blue; }
 span { color:red; }
 </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<span></span>

 <div></div>
<script>$(document.body).click(function () { $(document.body).append($("<div>"));
var n = $("div").size();
$("span").text("There are " + n + " divs." + "Click to add more.");}).click(); // trigger the click to start</script>
</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .size() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • If size() is to be kept, it should recalculate the actual length of the jQuery context. Currently, the following code will run forever. I would like to be able to execute the following without using .selector and .prevObject hacks to create a new jQuery context.

    <ul>
    <li> </li>
    <ul>

    $context = $("ul li");
    while($context.size() > 0) {
    $context.eq(0).remove();
    }
  • Porter
    If it were to also give the number of elements in an object, like this function:

    Object.prototype.size = function () {
    var len = this.length ? --this.length : -1;
    for (var k in this)
    len++;
    return len;
    }

    then it'd be handy.

    (Function snagged from http://stackoverflow.com/questions/5223/length-...)
  • I don't see the usage here, .length (as stated above) is faster, and more consistent to JavaScript in general, I'd like to see this getting deprecated as it serves no (useful) purpose in my opinion.
  • Yeah, this method is a "historical artifact" of sorts. The idea of deprecating it has been kicked around before, but it might be worth bringing it up again on the jQuery dev forum.