Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 235
Tomalak Avatar asked Dec 05 '25 15:12

Tomalak


2 Answers

.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; 
}; 
like image 102
Felix Kling Avatar answered Dec 07 '25 17:12

Felix Kling


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.

like image 33
Peter Ajtai Avatar answered Dec 07 '25 17:12

Peter Ajtai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!