How to check whether an element exists or not in jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery .length Property

You can use the jQuery .length property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>jQuery Test Element Exists or Not</title>
  • <script src=""></script>
  • <script type="text/javascript">
  • $(document).ready(function(){
  •     $("button").click(function(){
  •         if($("#myDiv").length){
  •             alert("The element you're testing is present.");
  •         }
  •     });
  • });
  • </script>
  • </head>
  • <body>
  •     <div id="myDiv"></div>    
  •     <p>The quick brown fox jumps over the lazy dog</p>
  •     <button>Check Element</button>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.