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

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:

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:

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).

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.

I am the co-founder and lead engineer at InVision App, Inc — the world's leading prototyping,
collaboration & workflow platform. I also rock out in JavaScript and ColdFusion 24x7 and I dream about
promise resolving asynchronously.