Search

How to tell if an element exists

Posted on 10th February 2009 — A common question for beginners coming to jQuery is: Is there a way to return true or false if an element exists? There is, and it’s (very, very) simple to do.

Watch

Watch the jQuery element exists screencast (Alternative flash version)

QuickTime version is approximately 10Mb, flash version is streaming.

View the demo used in the screencast

Finding an Element

All jQuery queries include a number of functions and properties. The length property is the one we’re interested in.

The simple test is:

$('element').length == 0; // no element found

For example:

<div>
  <p>Here is a picture of me: </p>
  <img src="images/remy.jpg" />
  <div id="debug"></div>
</div>
<script type="text/javascript">
  if ($('img').length) { // implies *not* zero
    log('We found img elements on the page using "img"');
  } else {
    log('No img elements found');
  }
  
  if ($(':input').length != 0) {
    log('Found an input-type element using ":input"');
  } else {
    log('No input-type elements found');
  }
  
  log('Looking for "div img", found ' + $('div').find('img').length);
    
  function log(msg) {
    $('#debug').append('<p>' + msg + '</p>');
  }
</script>

You can see our log function is simply outputting the string we give it. By using the .length property we can test whether an element exists, or whether it has been found in the page (or within a fragment of the document).

Works for all Queries

The length property is always available for any function that returns the jQuery object. For example, you can test the length property on .append(element), .css('color', '#c00'), etc.

However, the length property (to indicate element length), it’s available on the ‘getter’ functions, i.e. .val(), .css('color'), etc.