tags:

views:

25

answers:

2

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?

+5  A: 

.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; 
}; 
Felix Kling
Hm. Things can be so easy sometimes. :-)
Tomalak
This won't work if the `div` s are descendants of `$o`...
Peter Ajtai
@Peter: True, but in this point, the question was not clear. But I assume that the @Tomalak already knows `find`.
Felix Kling
@Felix: Exactly. :-) (@Peter: On my part, I assumed that "contained in the jQuery object" was unambiguous. jQuery objects are arrays, not tree structures, so strictly speaking there are no descendants.)
Tomalak
@Tomalak - I see what you mean. Thanks.
Peter Ajtai
+2  A: 

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.

Peter Ajtai
Nope. I wanted to count sub-sets, not everything. ;-)
Tomalak
@Tomalak - added it in.
Peter Ajtai
@Peter: +1 for the expanded answer.
Tomalak