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?
.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;
};
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.
.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()
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With