Categories

.size()

Categories: DOM Element Methods

.size()Returns: Number

Description: Return the number of elements in the jQuery object.

  • .size()

    version added: 1.0

The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

Given a simple unordered list on the page:

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

Both .size() and .length identify the number of items:

alert( "Size: " + $("li").size() );
alert( "Size: " + $("li").length );

This results in two alerts:

Size: 2

Size: 2

  • Count the divs. Click to add more.

    HTML:
    
    <span></span>
     <div></div>
    
    CSS:
    
      body { cursor:pointer; min-height: 100px; }
      div { width:50px; height:30px; margin:5px; 
            float:left; background:blue; }
      span { color:red; }
     
    Code:
    
    $(document.body)
    .click(function() { 
      $(this).append( $("<div>") );
      var n = $("div").size();
      $("span").text("There are " + n + " divs. Click to add more.");
    })
    // trigger the click to start
    .click();