How to use is() function in jQuery With Example

In this post, we will discuss how to use the jQuery is() method. This is an important filtering method used often in callback functions like event handlers.

jQuery is()

We use jQuery is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match otherwise returns false.

Here is the general syntax for using is();

filter could be string selector expression, function, elements or any existing jQuery object.

jQuery is() example

Following example demonstrates jQuery is() method usage.

In this example, you can see how is() method is used.

$( this ).is( "#sachin" ) : Here, is() method check if the selected element’s id="sachin".

$( this ).is( ".blue" ) : is() check if the selected element belongs to class="blue".

$( this ).is( ":contains('Dravid')" ) : Here is() checks whether the element contains a string “Dravid”.

$( this ).is( ".red,.grey" ) : This line of code checks whether the selected element belongs to class="red" or class="blue". The output will be same for Srinath and Kumble.

This will return true if it passes any of these conditions and display an output text with a sliding effect below the div elements. Otherwise executes the default condition. In our case, default condition executes when you click on Sanju
You can try passing function, jQuery object or any elements to the jQuery is() method.

You can try it yourself by clicking on any of the colored div elements below.

That’s all for now. We will discuss some more traversing techniques in the coming posts.

By admin

Leave a Reply

%d bloggers like this: