Online Snippets Library

Check The Element exist or not in jQuery

To Check The Element exist or not, we will use length property of jQuery.

Example

HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<title>Check The Element exist or not in jQuery</title>
</head>
<body>
<div id="div1">
<p>Div have id div1</p>
</div>
<div id="div3">
<p>Div have id div3</p>
</div>
<input id="button1" type="button" value="Check div1 exists?" />
<input id="button2" type="button" value="Check div2 exists?" />
</body>
</html>
Javascript
 $(document).ready(function(){
 $("#button1").click(function(){
 if($('#div1').length){
 alert("Div1 exists");
 }else{
 alert("Div1 does not exists");
 }
 });
$("#button2").click(function(){
 if($('#div2').length){
  alert("Div2 exists");
 }else{
  alert("Div2 does not exists");
 }
 });
  });