Open In App

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

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:




<!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:




Article Tags :