jQuery's is() Method Checks For Any Matching Elements

Posted October 1, 2009 at 2:14 PM

Tags: Javascript / DHTML

This is a really tiny post, but just something that I wanted to point out. The is() method in jQuery will return true if any of the elements in the current collection match any of the elements in the is-based collection (as defined by the given selector). Normally, if you're working with just a single element, there's no problem; but, if your current jQuery collection contains multiple elements, you might get an unintended result.

Take a look at this quick example:

 Launch code in new window » Download code as text file »

  • <!DOCTYPE HTML>
  • <html>
  • <head>
  • <title>jQuery is() Method</title>
  • <script type="text/javascript" src="jquery-1.3.2.js"></script>
  • <script type="text/javascript">
  •  
  • $(function(){
  •  
  • // Get all the paragraphs.
  • var p = $( "p" );
  •  
  • // Check to see if the Paragraph is cool.
  • if (p.is( ".cool" )){
  •  
  • // Highlight with gold.
  • p.css( "background-color", "gold" );
  •  
  • }
  •  
  • });
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • jQuery is() Method
  • </h1>
  •  
  • <p class="cool">
  • I am a cool paragraph.
  • </p>
  •  
  • <p class="boring">
  • I am a boring paragraph.
  • </p>
  •  
  • <p class="cool">
  • I am a cool paragraph.
  • </p>
  •  
  • </body>
  • </html>

Here, we are grabbing all of the paragraphs on the page, then we are checking to see if the collection is( ".cool" ). If so, then we are going to give it a gold background. When we run this code, this is what we end up with:

 
 
 
 
 
 
jQuery is() Method Returns true If Any Elements Match The Given Set. 
 
 
 

As you can see, all paragraphs, even the one with the class "boring" were given the gold background. This is because at least one element in the original collection matched at least one element in the is-based collection. Like I said, if you are working with a single node, then it's never a problem; but, if your original collection has several nodes, your is() method calls might give you a false positive.

That said, if you haven't used jQuery's is() method, it is totally awesome! I love it for checking classes, visibility, and tag types. Perhaps the coolest use-cases for me is using it in conjunction with the jQuery pseudo-selectors:

 Launch code in new window » Download code as text file »

  • if (elements.is( ":visible" )){ ... }

I love that one - I use it all the time in dynamic layouts.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Print Page



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Oct 1, 2009 at 3:19 PM // reply »
3 Comments

Ben, great post as usual. The is() method is also great for performance tricks.

Like maybe for a grid use case:

$("#somegrid").click(function(e){
if( $(e.target).is(".datarow") ){
// do something with this table row
}
});

So now instead of registering 50 or so table rows into the browser event model, you are only registering 1 element, and letting event delegation figure out the click.


Oct 1, 2009 at 3:21 PM // reply »
6,516 Comments

@Garrett,

Word up. I believe that is half the magic of how the live() event binding works.


Oct 1, 2009 at 7:00 PM // reply »
74 Comments

For that example wouldnt you do:

var p = $('p');

p.filter('.cool').css( 'background-color', 'gold' );

Because by doing:

if (p.is('.cool')) {
p.css( 'background-color', 'gold' );
}

You only check to see if there is some '.cool' p's available and so when you do this line:
p.css( 'background-color', 'gold' );

You are effectively applying the background to the 'p' set, rather than a filtered set.

That would be correct I suppose if you wanted to apply the gold background if there are any p's in the set with a class of cool.


Oct 1, 2009 at 7:16 PM // reply »
6,516 Comments

@shuns,

That is correct. The right/wrongness of the post wasn't so much what I was getting at. After all, I could simply do $( "p.cool" ) and have the exact set I was looking for; my real intention was only to point out that is() works with *any* overlap of the two sets and cannot speak for the entire collection, which may or may not lead to unintended results (depending on what you're doing).


Oct 2, 2009 at 2:46 PM // reply »
3 Comments

I just started using .is(':hidden') and .is(':visible') the other day.

Great explanation of what it actually does. Very helpful.

Keep it up.


Oct 2, 2009 at 5:04 PM // reply »
6,516 Comments

@Mark,

Yeah, those are great. jQuery's pseudo selectors are the best.


Oct 4, 2009 at 8:49 AM // reply »
2 Comments

My condution is "Only submit if at least one checkbox was checked."

In this state, i can use is() method.

$("#myform").submit(function(){
var chckbox = $('input[type="checkbox"]')
if(chckbox.is(":checked")){
return true;
}
else {
return false;
}
});

Like you said, This is a really tiny post, but useful...


Oct 4, 2009 at 8:08 PM // reply »
1 Comments

It was a very nice idea! Just wanna say thank you for the information you have shared. Just continue writing this kind of post. I will be your loyal reader. Thanks again.


Oct 5, 2009 at 2:40 AM // reply »
4 Comments

Hi,
jQuery is nice feature in JS.I am working on JS for some months.Your article and related comments are very helpful to me.


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 22, 2009 at 8:55 AM
Project HUGE: Trying Out A 4-Exercise Limit
Very informative. Thanks for the great post. ... read »
aha
Nov 22, 2009 at 7:42 AM
Using A Name Suffix In ColdFusion's CFMail Tag
Why not? ... read »
Nov 22, 2009 at 7:37 AM
Using A Name Suffix In ColdFusion's CFMail Tag
asd ... read »
Nov 22, 2009 at 4:30 AM
jQuery Live() Method And Event Bubbling
dasegtezr ... read »
Nov 22, 2009 at 4:03 AM
jQuery Live() Method And Event Bubbling
C_fieri ... read »
Nov 22, 2009 at 1:56 AM
Learning ColdFusion 9: Using CFQuery In CFScript Can Enable SQL Injection Attacks
Why adobe would give you script equivalent of cfquery is beyond me. I love cfquery tag because it helps me wriite clean sql, and get away from the horrible jdbc queries If I wanted to write javali ... read »
Nov 22, 2009 at 1:45 AM
Streaming Text Using ColdFusion's CFContent Tag And The Variable Attribute
The reason you would want to do this is to stream. Ack json/xml files to ria clients I used thus technique before because putting json in response stream causes debugging info to come thru As well a ... read »
Nov 21, 2009 at 6:47 PM
Hal Helms - Real World Object Oriented Development, Sarasota - Day Five
@charlie griefer, Thank you.. ... read »