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.



<!DOCTYPE html>
    <!-- JQuery CDN -->
    <script src=
      <h2 style="color:green">GeeksforGeeks</h2>
      <b>Check for element existence using jQuery</b><br/>
        <li class="gfg1">CSS</li>
        <li class="gfg3">HTML</li>
        <li class="gfg4">JQuery</li>
     <div id="resultID"></div>
      // 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!");
          $("#resultID").show().html("This element exist!");
      // Call check() function for li element having class gfg2.


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