How do you check if a selector matches something in jQuery?

Let's see how to check whether the selector provided matched something or not using jQuery?
Submitted by Pratishtha Saxena, on February 11, 2023

Firstly, let's understand what it means when it is said that the selector matches something. This indicates that for say a selector has been provided. It can either be an element name, class name, id name, etc. Therefore, if any kind of selector is provided, we need to check whether that selector exists in the document or not. If not, no actions can be performed on it.

To check this, we will consider the length property of jQuery. The length property will allow you to check whether there exist the elements whose selector has been provided. When an element exists, then its length will never be zero. It will contain something, hence, making "length>0. But if this property is not fulfilled, then we can say that the selector does not match anything in the document.

Syntax:

$('div').length;

The following example shows that if the provided selector matches with something in the document, then the CSS property will be changed. But if not, then no actions will be performed.

jQuery example to check if a selector matches something

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
    <style>
      div{
      background-color: slategrey;
      padding: 1%;
      font-weight: bold;
      font-style: italic;
      }
    </style>
  </head>
  
  <body>
    <h2>How do you check if a selector matches something in jQuery?</h2>
    <h4>Click the button to see if selector has selected something.</h4>
    <button>Click Here</button>
    <hr>
    <div>
      <p>Welcome to Include Help !</p>
      <p>This is a JavaScript Tutorial.</p>
      <p>Thanks for Visiting !</p>
    </div>
    <hr>
    <h4 id="one"></h4>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
    
            if ($('div').length){
                $('div').css('background-color','lightblue');
                $('h4#one').html('Div Selected');
            }
            else{
                $('h4#one').html('Nothing Selected');
            }
        });
    });    
  </script>
</html>

Output:

Example 1: How do you check if a selector matches something in jQuery?

After clicking on "Click Here" button.

Example 2: How do you check if a selector matches something in jQuery?



All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.