jQuery Traversal - is() Method
Example
Returns false because the parent element of the input is a p element:
var isFormParent = $("input[type='checkbox']").parent();.is("form"); $("div").text("isFormParent = " + isFormParent);
Definition and Usage
The is() method checks for a matching element collection based on a selector, element, or jQuery object. If at least one element in these matches the given parameter, it returns true.
Syntax
.is(selector)
Parameter | Description |
---|---|
selector | A string value containing a selector expression that matches elements. |
Detailed Explanation
Unlike other filtering methods, .is() does not create a new jQuery object. Instead, it allows us to check the jQuery object without modifying its content. This is usually useful within callbacks, such as event handlers.
Assuming we have a list with two items that contain child elements:
<ul> <li>list <strong>item 1</strong></li> <li><span>list item 2</span></li> <li>list item 3</li> </ul>
You can add a click handler to the <ul> element and limit the code to be triggered only when the list item itself, not the child elements, is clicked:
$("ul").click(function(event) { var $target = $(event.target); if ( $target.is("li") ) { $target.css("background-color", "red"); } );
Now, when the user clicks on the word "list" in the first list item or any word in the third list item, the clicked list item is set to have a red background. However, when the user clicks on "item 1" in the first list item or any word in the second list item, there is no change, because in the above cases, the event targets are <strong> is <span>.
Please note that for selector expression strings with positional selectors, such as :first, :gt(), or :even, the positional filtering is for the jQuery object passed to .is(), not for the document. Therefore, for the above HTML, expressions like $("li:first").is("li:last") return true, but $("li:first-child").is("li:last-child") returns false.
Using a function
The second usage of this method is to evaluate an expression of related elements based on a function rather than a selector. For each element, if the function returns true, the .is() method also returns true. For example, the following is a slightly more complex HTML fragment:
<ul> <li><strong>list</strong> item 1 - one strong tag</li> <li><strong>list</strong> item <strong>2</strong> - two <span>strong tags</span></li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
You can add a click handler to each <li> to calculate the number of <strong> elements within the clicked <li>:
$("li").click(function() { var $li = $(this), isWithTwo = $li.is(function() { return $('strong', this).length === 2; }; if ( isWithTwo ) { $li.css("background-color", "green"); } else { $li.css("background-color", "red"); } );