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. User Avatar
    Nathan
    Permalink to comment#

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


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

    • User Avatar
      Eliazer
      Permalink to comment#

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

    • User Avatar
      radiance

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

    • User Avatar
      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.

    • User Avatar
      ben
      Permalink to comment#

      pretty good.
      Thank you Nathan.

  2. User Avatar
    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()) { … }

    • User Avatar
      Chris happy
      Permalink to comment#

      Ummm, I think I see a spelling mistake in the last line of your comment:
      if ($(‘#myElemento).existe()) { … }
      is suppose to be
      if ($(‘#myElemento).exists()) { … }
      (existe compared to exists)

  3. User Avatar
    Jonathan Fontes
    Permalink to comment#

    Better,

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

  4. User Avatar
    El garch Hicham
    Permalink to comment#

    nice tuto :P

  5. User Avatar
    Skorney
    Permalink to comment#

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

  6. User Avatar
    Germano
    Permalink to comment#

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

    p.s. Exemple for multiple elements

  7. User Avatar
    jure

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

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

  8. User Avatar
    point
    Permalink to comment#

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

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

  9. User Avatar
    Jordi
    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)….

  10. User Avatar
    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

    • User Avatar
      Fyodor
      Permalink to comment#

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

  11. User Avatar
    fever

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

    • User Avatar
      Fyodor
      Permalink to comment#

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

  12. User Avatar
    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. User Avatar
    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. User Avatar
    David
    Permalink to comment#

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

  15. User Avatar
    Bert

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

  16. User Avatar
    Đan Trường
    Permalink to comment#

    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.

  17. User Avatar
    Max
    Permalink to comment#

    A useful post, especially the exists() function. Not explicitly mentioned above, but worth stating, the exists() method is chainable.

    A slight tweak/safety check to that would be to check that the first argument passed through is actually a function:

    $.fn.exists = function(callback) {
      var args = [].slice.call(arguments, 1);
    
      if (this.length && typeof callback === 'function') {
        callback.call(this, args);
      }
    
      return this;
    };
    

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag