How to check if an element exists in jQuery?

When we use dynamic elements in jQuery then sometimes you should check whether elements exits or not before performing a certain action on that element. In such cases, you can use jQuery .length property to determine if your selector matched anything in the webpage.
if ( $( "#idDiv" ).length ) { alert("idDiv exists!!"); }else{ alert("Does not exists!!"); }
<Div id="idDiv">Div selector with ID</div>
run this source code Browser View
Div selector with ID

Div selector with Class
Full Source
<html> <head> <title>jQuery if exists example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#bt1").click(function(){ if ( $( "#idDiv" ).length ) { alert("idDiv exists!!"); }else{ alert("Does not exists!!"); } }); $("#bt2").click(function(){ if ( $( ".classDiv" ).length ) { alert("classDiv exists!!"); }else{ alert("Does not exists!!"); } }); }); </script> </head> <body> <Div id="idDiv">Div selector with ID</div> <button id="bt1">Test ID Selector</button><br> <Div class="classDiv">Div selector with Class</div> <button id="bt2">Test Class Selector</button> </body> </html>

jQuery show() method

In jQuery , it isn't always necessary to test whether an element exists or not . The following code will show the element if it exists, and do nothing (with no errors) if it does not exists.
$("#idDiv" ).show();

Javascript

In JavaScript, you can use the following JavaScript to test whether an element exists or not.
if(document.getElementById("show()") !== null) { //code }