Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Check if Element Exists

if ($('#myElement').length > 0) { 
    // it exists 
}

Or to make it a fancy function with a callback:

// Tiny jQuery Plugin
// by Chris Goodchild
$.fn.exists = function(callback) {
  var args = [].slice.call(arguments, 1);

  if (this.length) {
    callback.call(this, args);
  }

  return this;
};

// Usage
$('div.test').exists(function() {
  this.append('<p>I exist!</p>');
});
​

Comments

  1. Permalink to comment#

    You don’t need the “> 0″, you can simply write:


    if ( $('#myElement').length ) {
    // it exists
    }

    • Eliazer
      Permalink to comment#

      No true, since jQuery always returns an object with length 0

    • radiance

      it’s true. If element exists: length > 0, and condition is true.
      If element not exosts: length = 0 and condition is false

    • Kevin Redman
      Permalink to comment#

      This IS correct. You do NOT need to say length > 0, because 1 = true, 0 = false.

      Eliazer, you probably just heard someone say “JQuery always returns an object” and thus you think that every FUNCTION of jQuery returns an object. jQuerys DEFAULT selector “$()” always does. However its functions don’t always… ie “has” and “is”… or “length”

      Length returns 0 or 1, and since 1 = true, 0 = false.

  2. Juan Trigueros
    Permalink to comment#

    Even easyest and reusable, you can define a function:

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

    And use it, anywhere, simple like this:

    if ($(‘#myElemento).existe()) { … }

  3. Better,

    if($(element).size()){
    // …
    }

  4. El garch Hicham
    Permalink to comment#

    nice tuto :P

  5. Skorney
    Permalink to comment#

    But why you don’t use $('#myElement')[0]? – returns the first DOM element or undefined, I think.

  6. Germano
    Permalink to comment#

    I use this:
    if($(“element”)[0] || $(“element”)[0])
    {
    // do something
    }

    p.s. Exemple for multiple elements

  7. i think “!=” is more performant than “>”, what do you think about?

    if ( $(‘#myElement’).length != 0 ) {
    // it exists
    }

  8. Permalink to comment#

    0 means ‘false’
    >= 1 means ‘true’

    if( $(‘#selector’).length )
    {
    //exec,if length >= 1
    }
    else
    {
    //exec,if length = 0
    }

  9. Permalink to comment#

    Hi folks, that checking is nice, but I am getting crazy looking how could I trigger that function when a element is created within the DOM context. Basicly I want stop #something.cycle when an iframe appears on my document (from js live editor)….

    • N8
      Permalink to comment#

      Jordi,
      Did you very figure out how to trigger a function when an element is created? I am running into this issue myself, and not finding much that would help.

      Thank you,
      -N8

  10. Avennida Gez

    Guys, I have used this and does not work
    it is not detected

    if($(‘#body’).length) bla bla
    of course if I use and id body in body tag works, but if it does not have the id=’body’ this detector does not work at all

    • Fyodor
      Permalink to comment#

      always means that your matching the id. you should use $(‘body’) instead of $(‘#body’)

  11. fever

    Is this function working with “live” or “bind”?

    • Fyodor
      Permalink to comment#

      I haven’t checked but it should since it’s returning ‘this';

  12. Amrit Deep
    Permalink to comment#

    Hey, this code doesn’t work
    $(‘#stop’).bind(‘click’, function(){
    stopMove();
    jQuery.fn.exists = function(){return this.length>0;}

        if($('#fifteen').exists()){
            alert("fifteen");
        }
        else if($('#thirty').exists()){
            alert("thirty");
        }
        else if($('#forty_five').exists()){
            alert("forty_five");
        }
        else if($('#sixty').exists()){
            alert("sixty");
        }
        else {
            alert("nothings");
        }
    
  13. Ripul
    Permalink to comment#

    Need a little help. I have used it approx 1000 times but still can not get it right this time:
    My if statement looks like this:

    if($(‘#s’+user_id + ‘ .course_stats_user’).length > 0){

    }

    ‘#s’+user_id + ‘ .course_stats_user’ does not exist but still it goes in the if loop…any ideas..

    NVM.. it is now resolved..

  14. David
    Permalink to comment#

    I spent so long futzing with this… Leave it to CSS-Tricks to distribute valuable knowledge. Thank you!

  15. Bert

    Using .exists() seems the logical choice over .length, no?

  16. I see a lot of way in discussion to check ID of div using jquery.
    I tried test and all of them is correct.
    I using if( $(‘#myElement’).length) to quick in use.
    Thank for nice post.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```