Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to checks the current selection against an expression using jQuery ?

  • Last Updated : 05 Nov, 2021

The task is to check the current selection against an expression using jQuery. jQuery is a lightweight and fast JavaScript that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript.

jQuery is widely famous for its motto of “Write less, do more.” In simple words, by writing a few lines of code you can achieve your goal. 

In jQuery, we can use the is(selector) method that checks the current selection against an expression and returns true if at least one element of the selection fits the given selector. Remember that if no element fits, or the selector is not valid, then the response will be ‘false‘.

Syntax: 

element.is( selector )
  • selector: The expression to filter.

 

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script type="text/javascript" src=
    </script>
  
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("li").click(function () {
                if ($(this).is(":first-child")) {
                    $("h2").text("This is list item 1");
                } else if ($(this).is(".middle0,.middle1")) {
                    $("h2").text("This is middle class list");
                } else if ($(this).is(":contains('item 5')")) {
                    $("h2").text("It's 5th list");
                } else if ($(this).is(":contains('item 6')")) {
                    $("h2").text("It's 6th list");
                }
            });
        });
    </script>
  
</head>
  
<body>
    <div>
        <h1 style="color:green;text-align:center">
            GeeksforGeeks
        </h1>
  
        <span style="color:green:">
            Click any list item below:
        </span>
          
        <ul>
            <li class="top0">list item 1</li>
            <li class="top1">list item 2</li>
            <li class="middle0">list item 3</li>
            <li class="middle1">list item 4</li>
            <li class="bottom0">list item 5</li>
            <li class="bottom1">list item 6</li>
        </ul>
  
        <h2 style="color:green;
                   text-align:center;
                   background-color:lightgreen;">
            FILLER
        </h2>
    </div>
</body>
  
</html>

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!