Tomalak
Tomalak

Reputation: 338148

How to count all elements of a certain type in a jQuery object?

Say I have a jQuery object of uncertain contents (from something that could be a dynamic selector or a string of HTML):

var $o = $(something);

Now, for example how do I count how many <div> objects are contained in the jQuery object itself (i.e. no descendants of the contained elements)? I could do

var l = $o.filter( function () { return $(this).is("div"); } ).length;

Other ideas?

Upvotes: 2

Views: 7361

Answers (2)

Peter Ajtai
Peter Ajtai

Reputation: 57685

There are two ways to count elements of a certain type within a jQuery object. Which method you use depends on your definition of in.

  1. .find().length - Find all descendants of the DOM element/s represented by the jQuery object fitting a pattern. Can also use a context of the form $(this, that) to find this within that. It's implemented using .find()

  2. .filter().length - Reduce the set of selected DOM elements represented by the jQuery object to only include ones that match a pattern.


If you want to search for descendants in the object, use .find() or a context:

$o.find("div").length

or

$("div", $o).length

For example

<li>
    <div></div>
    <div></div>
</li>

For the above:

$("li").find("div").length // This is 2
$("div", "li").length      // This is 2

$("li").filter("div").length // This is 0

If you want to reduce the number of selected items by a rule, use .filter()

<div class="a"></div>
<div></div>

For the above

$("div").filter(".a").length // This is 1

$("div").find(".a").length // This is 0
$(".a", "div").length      // This is 0

jsFiddle showing both .find() and .filter() at work.

Upvotes: 7

Felix Kling
Felix Kling

Reputation: 816302

.filter() takes a selector, so

$o.filter('div')

should actually be sufficient.

And of course you could create a plugin for that:

$.fn.count = function(selector) {  
    return this.filter(selector).length; 
}; 

Upvotes: 7

Related Questions