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

Posted October 1, 2009 at 2:14 PM by Ben Nadel

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:

  • <!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:

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

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



Reader Comments

Oct 1, 2009 at 3:19 PM // reply »
5 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 »
11,314 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 »
76 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 »
11,314 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 »
4 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 »
11,314 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.


Dec 9, 2009 at 5:17 AM // reply »
3 Comments

Great post. Just now saw the .is method on 24ways.org and didn't know it. Tried finding it in the Jquery api reference but it's nowhere to be found. This post really helped me out. Thanx.

Should anyone find the doc page on the jquery site please post it here.


Dec 9, 2009 at 5:20 AM // reply »
3 Comments

LOL just found it:

docs.jquery.com/Traversing

Hope somebody finds this helpfull


Mar 5, 2010 at 12:54 PM // reply »
1 Comments

Hi Ben... i always read your blog, and specially this post has solved a problem i had that was gettin me nuts!

Thanks a lot and keep the good work.

Greets from Chile, South America.

Rod.


Mar 8, 2010 at 7:07 PM // reply »
11,314 Comments

@Rodrigo, @Ryan, @Huile, @Ed,

Glad you guys enjoyed the post. $().is() is such a hugely useful method!


Nov 20, 2010 at 9:39 PM // reply »
1 Comments

thank you


Nov 22, 2010 at 3:30 AM // reply »
3 Comments

Been away for a while Ben :)

Keep a lookout for the new 24 ways 2010 edition on 24ways.org


Dec 24, 2011 at 3:49 PM // reply »
1 Comments

well, this isn't very helpful because you never mention the solution to working with more than one element, you just say that .is() isn't good for multiple elements, but you don't explain what would get us the result with multiple elements.



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Jun 18, 2013 at 9:20 PM
Mapping AngularJS Routes Onto URL Parameters And Client-Side Events
I couldn't find examples of passing multiple arguments using the when() routing statement so figured out through trial and error that you can pass multiple arguments using the following format: .whe ... read »
Jun 18, 2013 at 3:39 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
Hi Ben, THANKS! While not bleeding edge, it is new to me & I like learning new things every day! ... read »
Jun 18, 2013 at 12:30 PM
Disabling Auto-Correct And Auto-Capitalize Features On iPhone Inputs
Also spellcheck="false" should be mentioned as part of html5 specs ... read »
Jun 18, 2013 at 8:40 AM
Using Named Functions Within Self-Executing Function Blocks In Javascript
Hi Ben, you forgot to mention the most important thing for named self-executing functions - they can be referenced by name ONLY inside their execution context (which is parens in this case), it mean ... read »
dee
Jun 18, 2013 at 7:01 AM
My Safari Browser SQLite Database Hello World Example
hai ben, this program is really good i could understand the concept but i dint know how to save it and how to open it as you have done in the video can u give that details pls ... read »
Jun 18, 2013 at 6:04 AM
Clearing Inline CSS Properties With jQuery
Thanks a lot for for post! It helped me a lot... after being stuck since 24 hrs.. found solution from your post. Thanks again! ... read »
Jun 18, 2013 at 2:31 AM
SOTR 2013 - The Best Conference I Never Went To
I keep watching it, should keep me happily distracted until SotR14 ;) ... read »
Jun 17, 2013 at 9:45 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, As I was reading what you wrote, it occurred to me that maybe I do something similar to that in some of my client-side code. In an application I'm working on, there are a bunch of unrelated ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools