jQuery check if an element exists or not

If you use a jQuery selector it will always return an array object even if its empty so if you try to do something like this
if($(selector)) {
 //object exists
} 
else {
 //object does not exists
}

it will not work as it will return array object so checking for that object will always be true. You have to use the length property of the object to see if it exists or not. 
if($(selector).length > 0) {
 //object exists
} 
else {
 //object does not exists
}
 
Here is an example ...


jquery check if element exists

<html>
<head>
<title>jQuery check if element exists or not</title>

<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />

<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function() {
  
  $('#myButton').click(function() {
       
      $("#myResults").html("");
    
      if ($('#myInputText').length > 0){
    $("#myResults")
    .append('My Input Text with id="myInputText" exists!<br/>');
      }
      else {
       $("#myResults")
       .append('My Input Text with id="myInputText" does not exists!<br/>');
      }
      
      if ($('a').length > 0){
    $("#myResults").append('&lt;a&gt; element exists!');
      }
      else {
       $("#myResults").append('&lt;a&gt; element does not exists!');
      }
      
  });
     
 });       
    </script>
</head>
<body>
 <div id="myExample">
  <form id="myForm" action="">
   <fieldset>
    <legend>jQuery Get and Set input Text value</legend>

    <p>
     <label for="myInputText">
      Just an input Text box:
     </label><br /> 
     <input
      id="myInputText" type="text" name="inputBox" />
    </p>
    <input id="myButton" type="button"
      value="Click here to see results" />
   </fieldset>
   <fieldset>
    <legend>See Result in this Section:</legend>
    <div id="myResults"></div>
   </fieldset>
  </form>
 </div>
</body>
</html>

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.