Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to make jQuery throw an error when it doesn’t match an element ?

  • Last Updated : 26 May, 2021

In this article, we will learn how to make a jQuery throw error when it does not match an element.

Approach: To do this task we create a function and check if the given element exists or not, using the length property of the element. If an element exists the length of the element is greater than or equal to 1 otherwise the length of the element is 0. So if the element exists we display a message otherwise we throw an error. We call the function before we use that element. If the element doesn’t exist then we get an error.

Example:

HTML




<!DOCTYPE html>
<html>
  <head>
      
    <!-- JQuery CDN -->
    <script src=
    </script>
    
  </head>
  
  <body>    
      <h2 style="color:green">GeeksforGeeks</h2>
      <b>Check for element existence using jQuery</b><br/>
      <ul>
        <li class="gfg1">CSS</li>
        <li class="gfg3">HTML</li>
        <li class="gfg4">JQuery</li>
      </ul>
      
     <div id="resultID"></div>
      
    <script>
      // Create a function that checks if the element exists or not.
      $.fn.check = function(){
        if(this.length === 0){
           
          $("#resultID").show().html("This element does not exist!");
        }
        else
        {
          $("#resultID").show().html("This element exist!");
        }
      }
      // Call check() function for li element having class gfg2.
      $('li.gfg2').check();
    </script>
  </body>
</html>

Output:

  • When we use the function check() with list item with “gfg2” class that does not exist in the above code.
  • When we use the function check() with list item with “gfg3” class that exists in the above code.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!