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.

Demo

If you find this demo doesn't work as expected, it's possibly due to the demo running from within an iframe. Try running the demo in it's own window.

Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Test if an element exists</title>
<style type="text/css" media="screen">
    body { font-family: helvetica; }
</style>
<script src="jquery-1.3.1.js" type="text/javascript"></script>
</head>
<body>
<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 + ' elements');

  function log(msg) {
    $('#debug').append('<p>' + msg + '</p>');
  }
</script>
</body>
</html>

Comments

  1. BinaryKitten On 10th February 2009 at 18:02

    i have that added to my standard include file …

    jQuery.fn.exists = function() { return (this.length > 0); };

    so for legibility i can do if($(’#object’).exists()) {

  2. Stan On 10th February 2009 at 18:02

    $(selector).size() exists for this purpose as well… It wraps the length property, but since it’s officially part of the jQuery API it would be better to use moving forward when the presence of the length property might disappear but the method call won’t.

    Furthermore… perhaps a better solution for the above instead of an ‘exists’ method would be a method which silently and politely doesn’t execute the following condition, if the method doesn’t exist… I’ve often wished there were chainable if() else() methods for binding into jQuery.

  3. Remy On 10th February 2009 at 18:02

    @Stan - yes and no - but definitely ‘yes’, actually there is a function that does it - but the API does say this about .size():

    However, it is slightly slower, so length should be used instead.

    And the length property is also part of the API (i.e. it’s documented as such), so it’s no more likely to be dropped.

    Of course you can still chain and it does matter if the elements go down to zero. However, it is required when you need to pull an attribute out of the element you’re aiming to find - which I can see that’s where you’re saying you’re like a silent fail (though, personally, I’m not sure how this would work in practise).

  4. James On 10th February 2009 at 19:02

    I usually just test for the first element (zero index), like: if($('element')[0]) {…}

  5. BinaryKitten On 10th February 2009 at 19:02

    for chainability…

    jQuery.fn.IfExists = function() { if(this.length > 0) return this; };

  6. shin On 10th February 2009 at 19:02

    Oh, you look like Jack Bauer in 24. :-)

  7. Tomas On 10th February 2009 at 20:02

    function log(msg) { console.log(msg); }

    For FireBug. :)

  8. Andreas On 10th February 2009 at 23:02

    just to make it clear, the .length property exists because $() queries always returns standard javascript arrays, so theres no magic with the .length, which is why its the fastest option.

    if you look at the jquery file you see that size is defined as

    size: function() {
        return this.length;
    },
    

    and its “slower” because its a extra function call while .length is pure js property of Array.

  9. Remy On 11th February 2009 at 00:02

    @James - you should be very wary of using if ($('element')[0]) { as this makes the assumption that the selector has at least one element. If the selector returned zero elements, then the code would break.

    @Andreas - spot on. I’d say an augmented array, but an array none the less - which is exactly why there’s no magic - this is actually wrong, and I’m clarifying below. The thing is, most new users to jQuery won’t spot that it’s actually returning an array, hence the questions on the #jquery IRC channel and the post ;-).

    @Shin - you’re mad, Jack Bauer doesn’t look anywhere near as cool as me :-P

  10. Karl Swedberg On 11th February 2009 at 01:02

    @andreas - Actually, $() returns an object, not an array. It is an “array-like” object, because it has a length property, but it’s not a true array.

  11. Remy On 11th February 2009 at 14:02

    Karl’s correct here. I’ve spoken to John about this to understand exactly what it is too.

    Here’s the deal:

    jQuery is an object that is, as Karl said, “array-like”.

    The reaon isn’t array-like is because methods are borrowed from the Array.prototype.

    The length property is never explicitly set in the jQuery library, but that’s because the push method updates the length property.

    Very sneaky of JavaScript, but sneaky-clever :-)

  12. James On 11th February 2009 at 17:02

    @Remy, I don’t understand how this: if ($('element')[0]) { would break…?

    $('element') will always return something, testing it for a property like [0] will return either the first element or ‘undefined’ if it doesn’t exist - and since ‘undefined’ is a “falsey” value the expression will evaluate to false (!!$('element')[0] === false)).

    It would only break if I assumed that the first element existed, something like this: if($('element')[0].nodeName){…}.

  13. Remy On 11th February 2009 at 17:02

    @James - sorry, you’re right, it doesn’t break, but it’s syntax I would recommend to avoid - only because it eventually leads to $('elm')[0].nodeName - which I’ve seen in teams before.

    It could also create a false positive, if the first element in the list were to be false - I know this won’t particular happen in jQuery, but it’s syntax I would personally avoid.

  14. Liam Goodacre On 11th February 2009 at 18:02

    @Stan …is this what you mean by chain-able ‘if else’ methods? I find this really useful…

    /* –idea– if test is true then run the funcIfTrue method else run the funcIfFalse method return */ jQuery.fn.iif = function(test, funcIfTrue, funcIfFalse) { // if test is true, then run true func, else run false func if (test) { funcIfTrue; } else { funcIfFalse; }

    // return
    return this;
    

    }

    …and obviously you can also do this:

    jQuery.fn.iif = function(test, funcIfTrue) { // if test is true, then run true func if (test) { funcIfTrue; }

    // return
    return this;
    

    }

  15. Poch Bou On 27th May 2009 at 14:05

    Good that is what I really want.

    Thanks you!

  16. Elemental Web and Mobile Solutions On 10th July 2009 at 08:07

    Thanks for the post. It was quite simple but effective.

    I was wondering how you could get a list of DIV’s for example as an element array and then change CSS of one of the elements (EG: the second one).

    Elemental

  17. Luis Aveiga On 28th October 2009 at 05:10

    Thanks for the post! Just what I was looking for. BTW Nice website, good work.

  18. Eugene On 13th November 2009 at 02:11

    I was using .size() what is the difference, which is better?

    Thanks.

    Update: Just saw other comments, got it now :)

  19. Newbie On 15th November 2009 at 00:11

    Thanks for this great tip. I’ve been wondering how this could be done in jQuery. In prototype all I have to do is for e.g. if($(’idofelement’)) { //blah di blah }. I was using the same construct for jQuery and found out one time that it doesn’t actually do what I thought it does.

  20. Ayush Saran On 20th November 2009 at 13:11

    Thanks this has helped tremendously

  21. Robert Erdmann On 29th November 2009 at 14:11

    Very cool! Needed that to make my day! Exactly what I was looking for. And espacially awesome to watch it working! I have to search more on your site in future. ;)

    Have a nice day! Robert from Leipzig, Germany

  22. The Gator On 5th January 2010 at 00:01

    Thanks — just what I was looking for!

  23. Arnz On 6th January 2010 at 17:01

    Nice one. Simple but effective. thanks

Leave your own comment
  • http://