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.



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">
    <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=""></script>
      background-color: slategrey;
      padding: 1%;
      font-weight: bold;
      font-style: italic;
    <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>
      <p>Welcome to Include Help !</p>
      <p>This is a JavaScript Tutorial.</p>
      <p>Thanks for Visiting !</p>
    <h4 id="one"></h4>
  <script type="text/javascript">
            if ($('div').length){
                $('h4#one').html('Div Selected');
                $('h4#one').html('Nothing Selected');


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 All rights reserved.