views:

82

answers:

4

If I have a selector like

$.('.active');

How can I see how many items that matched?

Alternatively, is there an easy way to see if more than zero elements were matched?

+3  A: 

call .length on the returned set.

x1a4
+2  A: 

You can use the native javascript length property:

alert( $(".active").length );

You can even use the .length return value directly within a conditional statement:

if( $(".active").length ) {
  alert("Found some");  
} else {
  alert("Found nothing"); 
}​

In this example, if 0 results are found the else statement will be executed.

Example: http://jsbin.com/upabu/edit

Jonathan Sampson
+2  A: 

How many:

var count = $('.active').length;

Check if it matched something:

if ($('.active').length) // since 0 == false
Matthew Scharley
+1  A: 

you should use $('.class').length because it is faster, but alternatively you can call $('.class').size() and get the same result.

To check the elements, do something like the following:

var len = $('.class').length;
if (len)
    // do something
else
    // do something else

Caching the length in a local var is an optimization that will speed up your JS if you have to make another call to that length property.

Jason