Take the 2-minute tour ×

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length>0) {
    // Do something

Is there is a more elegant way to approach this? Perhaps a plugin or a function?

share|improve this question
if ($(selector).length) {} is the most elegant and the fastest. –  gradbot Jun 21 '10 at 3:21
Note: In jQuery versions older than 1.4, $('').length // is 1 (ref). So in that case use $(selector || []).length. –  Mottie Feb 21 '13 at 18:43
if($(selector)[0]) {} I always use this.. –  Mr_Green Sep 4 '13 at 11:57
To avoid recursion maybe it will be best: if ( !$(selector).length ) { return; } // Do something –  Gabotron Nov 29 '13 at 15:22
@bergie3000 You're testing the selector speed and not the comparison. jsperf.com/length-vs-length-0-for-existence-of-element/2 –  gradbot Feb 21 at 3:41

21 Answers 21

In JavaScript, everything is truthy or falsy and for numbers, 0 means false, everything else true. So you could write:

if ($(selector).length)

and you don't need that "> 0" part.

share|improve this answer
This is the best method, fastest and simplest. –  Skone Dec 4 '09 at 1:16
@MrBoJangles: What makes this the "best" answer? You prefer it over the others, but that doesn't mean everyone else does. I would submit to you that, on average, the "best answer" is the one that is voted to the top. –  sohtimsso1970 Apr 24 '11 at 16:10
This is the idiomatic code. The golden monkey, sans the pedantic stew in which we sometimes steep ournselves. This is the git 'r done answer. Some questions lend themselves to discussion. Some just have an answer, like a simple math equation. All the cool kids are using this answer. So let it be written. So let it be done. –  MrBoJangles Apr 29 '11 at 22:09
This is the least readable solution. That said I still use it out of laziness. –  Muhd Nov 5 '11 at 0:40
I agree.. this is the correct answer. Theres no reason to leave your arg to goto a function to return true or false. If you don't understand what "length" is then you shouldn't be coding =p –  rkingon Dec 6 '12 at 21:20
up vote 689 down vote accepted


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

if ($(selector).exists()) {
    // Do something

There you go!

This is in response to: Herding Code podcast with Jeff Atwood

share|improve this answer
I just write: if( $(selector).length ){ ... } without the '> 0' –  vsync Nov 24 '09 at 9:22
Your $.fn.exists example is really, really horrible, and I hope nobody uses it. You’re replacing a property lookup (cheap!) with two function calls, which are much more expensive—and one of those function calls recreates a jQuery object that you already have, which is just silly. –  C Snover May 30 '10 at 4:14
@redsquare: Code readability is the best rationale for adding this sort of function on jQuery. Having something called .exists reads cleanly, whereas .length reads as something semantically different, even if the semantics coincide with an identical result. –  Ben Zotto Aug 2 '10 at 20:52
@quixoto, sorry but .length is a standard across many languages that does not need wrapping. How else do you interpret .length? –  redsquare Aug 3 '10 at 0:13
In my opinion, it's at least one logical indirection from the concept of "a list length that is greater than zero" to the concept of "the element(s) I wrote a selector for exist". Yeah, they're the same thing technically, but the conceptual abstraction is at a different level. This causes some people to prefer a more explicit indicator, even at some performance cost. –  Ben Zotto Aug 3 '10 at 0:29

If you used

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

you would imply that chaining was possible when it is not.

This would be better:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

Alternatively, from the FAQ:

if ( $('#myDiv').length ) { //Do something }

You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.

if ( $('#myDiv')[0] ) { //Do something }
share|improve this answer
The first method reads better. $("a").exists() reads as "if <a> elements exist." $.exists("a") reads as "if there exists <a> elements." –  strager Jan 14 '09 at 20:00
true but again, you're implying that chaining is possible and if I tried to do something like $(selector).exists().css("color", "red") it wouldn't work and then I would be =*( –  Jon Erickson Jan 15 '09 at 0:31
There are already methods that aren't chainable, like attr and data functions. I do see your point though and, for what it's worth, I just test for length > 0 anyways. –  Matthew Crumley Jan 16 '09 at 5:42
Why on earth would you need to chain this? $(".missing").css("color", "red") already does the right thing… (i.e. nothing) –  Ben Blank Sep 8 '10 at 6:43
First example ($('.mySelector').length) works fine, no need to create an exists() wrapper for it. –  nickb Sep 14 '10 at 19:16

You can use this:

// if element exists
if($('selector').length){ //do something }

// if element does not exist
if(!$('selector').length){ //do something }
share|improve this answer
Did you not see that Tim Büthe had already given this answer 2 years prior to you? –  Th4t Guy Jul 31 at 17:28

The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:

if (document.getElementById('element_id')) {
    // Do something

It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.

And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.

NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).

share|improve this answer
Totally not the same thing. JQuery selectors can be used for any CSS rule - for example $('#foo a.special'). And it can return more than one element. getElementById can't begin to approach that. –  kikito Mar 7 '12 at 16:30
You are correct in that it isn't as broadly applicable as selectors. However, it does the job quite well in the most common case (checking if a single element exists). The arguments of self-explanation and speed still stands. –  Magne May 10 '12 at 8:55
WHile I prefer the Jquery method I always like seeing the original raw method of doing things! Gives more understanding when you see Jquery doing stuff. –  PerryCS Feb 10 '13 at 3:04
@Noz if(document.querySelector("#foo a.special")) would work. No jQuery needed. –  Blue Skies Dec 8 '13 at 0:43
The argument of speed in JS engines is only dead in the mind of people who can't function without jQuery, since it's an argument they can't win. –  Blue Skies Dec 8 '13 at 0:45

You can use:

if ($(selector).is('*')) {
  // Do something

A little more elegant, perhaps.

share|improve this answer
This is too much for such a simple thing. see Tim Büthe answer –  vsync Nov 24 '09 at 9:28

Extreme Update Oct 2, '13

Originally I made this plugin to provide a bit more acute sense than simply if ($(ele).length) { /* DO WORK */ }. Sure that is simple and easy, but I didn't like how it took me "outside" of typical "jQuery style". I really wanted a $.fn.exist() method in order to maintain readable markup. Also, the simple plugins so often previously suggested, do not account for developer error. Thus the creation of the very simple plugin found here (minified).

I soon decided to kick it up a notch and provide for more functionality in checking against developer mistakes as well as provide a bit more functionality. The thought lead me to the update on Jun 6, '13 found over here (minified). Now I've finally put together a version I really like!

This new version of the plugin can still be used as simple as if ($(ele).exist()) { /* DO WORK */ }, however I found that to be a bit "against the grain" with jQuery typical markup style. I thought, "Why the if statement? Shouldn't that be in a callback?" Now it is! Behold, the new, bigger, stronger, callbackier $.exist() Plugin!



;;(function($) {
    if (!$.exist) {
            exist: function() {
                var ele, cbmExist, cbmNotExist;
                if (arguments.length) {
                    for (x in arguments) {
                        switch (typeof arguments[x]) {
                            case 'function':
                                if (typeof cbmExist == "undefined") cbmExist = arguments[x];
                                else cbmNotExist = arguments[x];
                            case 'object':
                                if (arguments[x] instanceof jQuery) ele = arguments[x];
                                else {
                                    var obj = arguments[x];
                                    for (y in obj) {
                                        if (typeof obj[y] == 'function') {
                                            if (typeof cbmExist == "undefined") cbmExist = obj[y];
                                            else cbmNotExist = obj[y];
                                        if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
                                        if (typeof obj[y] == 'string') ele = $(obj[y]);
                            case 'string':
                                ele = $(arguments[x]);

                if (typeof cbmExist == 'function') {
                    var exist =  ele.length > 0 ? true : false;
                    if (exist) {
                        return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
                    else if (typeof cbmNotExist == 'function') {
                        cbmNotExist.apply(ele, [exist, ele]);
                        return ele;
                    else {
                        if (ele.length <= 1) return ele.length > 0 ? true : false;
                        else return ele.length;
                else {  
                    else return ele.length; 

                return false; 
            exist: function() {
                var args = [$(this)];
                if (arguments.length) for (x in arguments) args.push(arguments[x]);
                return $.exist.apply($, args);


The use is extremely easy. You can still use in an if: statement, or you can create your own callback. Keep in mind, the callback has 2 possible creations. You can create the call back with NO PARAMETERS such as function() {} and it will ONLY FIRE IF the element EXIST. However, if you provide a parameter, such as function(exist) {} or even function(bob) {}, then the callback will ALWAYS FIRE even if the element does NOT EXIST. In the second scenario, your parameter, no mater what you name it, becomes a BOOLEAN of wether or not the element exist.

UPDATE: After a little more personal use, I found the "parameter" setup to be a bit flawed. I've since replaced it with a better working ideal of allowing for a "second" function. The second function will fire if the element does NOT exist. However, if you choose to set only one function, then it will only fire when the element exist. Thus the "chain" will die if the selected element does "not" exist. Of course, if it does exist, the first function will fire and chainability will continue.

On another note, keep in mind, using a callback method helps to maintain chainability. This means the element is returned and you can continue chaining commands as with any other jQuery method!


Example Uses

if ($.exist('#eleID')) { /* DO WORK */ }        //  param as STRING
if ($.exist($('#eleID'))) { /*  DO WORK */ }    //  param as jQuery OBJECT
if ($('#eleID').exist()) { /*   DO WORK */ }        //  enduced on jQuery OBJECT

$.exist('#eleID', function() {          //  param is STRING && CALLBACK METHOD
    /*  DO WORK */
    /*  This will ONLY fire if the element EXIST    */
}, function() {         //  param is STRING && CALLBACK METHOD
    /*  DO WORK */
    /*  This will ONLY fire if the element DOES NOT EXIST   */

$('#eleID').exist(function() {          //  enduced on jQuery OBJECT with CALLBACK METHOD
    /*  DO WORK */
    /*  Will ONLY FIRE IF EXIST */

$.exist({                       //  param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD
    element: '#eleID',
    callback: function() {
        /*  DO WORK */
    /*  This will ONLY fire if the element EXIST    */

Minified jsFiddle

;;(function($){$.exist||($.extend({exist:function(){var a,c,d;if(arguments.length)for(x in arguments)switch(typeof arguments[x]){case "function":"undefined"==typeof c?c=arguments[x]:d=arguments[x];break;case "object":if(arguments[x]instanceof jQuery)a=arguments[x];else{var b=arguments[x];for(y in b)"function"==typeof b[y]&&("undefined"==typeof c?c=b[y]:d=b[y]),"object"==typeof b[y]&&b[y]instanceof jQuery&&(a=b[y]),"string"==typeof b[y]&&(a=$(b[y]))}break;case "string":a=$(arguments[x])}if("function"==typeof c){var e=0<a.length?!0:!1;if(e)return a.each(function(b){c.apply(this,[e,a,b])});if("function"==typeof d)return d.apply(a,[e,a]),a}return 1>=a.length?0<a.length?!0:!1:a.length}}),$.fn.extend({exist:function(){var a=[$(this)];if(arguments.length)for(x in arguments)a.push(arguments[x]);return $.exist.apply($,a)}}))})(jQuery);

NOTE: All minified versions were made using Google Closure

share|improve this answer
+1 for thought.. –  rkingon Dec 6 '12 at 21:23
$.exist("myID") - this is a terrible idea. –  kajacx Aug 22 '13 at 16:36
@kajacx why? just saying "this is a terrible idea" to an answer that has already grown quite popular and i've been using for almost 2 years now, doesn't really help. Please provide a "constructive" reason "why". Otherwise there is no reason to change it, as it works great and allows more of the "openness" JS developers are already used too. –  SpYk3HH Aug 22 '13 at 16:49
@kajacx agreed and understand, but that doesn't make the feature any more horrible. It's not a "recommended" way of doing things, but having "myID" default to "#myID" isn't so horrible when its understood ahead of time that that will happen, however "div" will automatically go to div tags before it calls on an ID named "div", so, yea that could be a problem, but a rarity. Allowing for "myID" to default to "#myID" was simply a "side-effect" in how I setup the initializer and not necessarily "horrible", just not recommended, though existent, none the less. –  SpYk3HH Aug 23 '13 at 12:52
Using quotation marks for emphasis is a terrible idea. ;) –  TRiG Feb 14 at 13:23

There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:

if(document.getElementById("myElement")) {
    //Do something...

If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.

jQuery is really cool, but don't let pure JavaScript fall into oblivion...

share|improve this answer
I know: it doesn't answer directly the original question (which asks for a jquery function), but in that case the answer would be "No" or "not a semantically correct solution". –  amypellegrini Nov 14 '11 at 14:24
This code is plain wrong and breaks the functionality of document.getElementById; I sure hope you mean if (document.getElementById('myElement')) { –  Ja͢ck Jan 21 '13 at 2:43
Jack: I've corrected my answer... Thanks for pointing out such an awful error, I gess I should sleep more! –  amypellegrini Apr 29 '13 at 3:28

I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.

var $target = $({});        
console.log($target, $target.length);

// Console output:
// [▼ Object              ] 1
//    ► __proto__: Object

My only suggestion is to perform an additional check for {}.

if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');

I'm still looking for a better solution though as this one is a bit heavy.

Edit: WARNING! This doesn't work in IE when selector is a string.

$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
share|improve this answer
How often do you find yourself calling $() with an empty object as an argument? –  nnnnnn Dec 22 at 11:24
@nnnnnn Actually never (I don't use jQuery anymore). But I guess 3 years ago I had a case of exposing an API that would take a selector and return the number of elements for that selector. If another dev would pass in an empty object, it would incorrectly respond with 1. –  Oleg Dec 22 at 15:03
$(selector).length && //Do something
share|improve this answer

You could use this:

    exists: function() { return this.length }

if($(selector).exists()){do something}
share|improve this answer

I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..

// Checks if an object exists.
// Usage:
//     $(selector).exists()
// Or:
//     $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
share|improve this answer

You can save a few bytes by writing:

if ($(selector)[0]) { ... }

This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.

share|improve this answer

How about:

function exists(selector) {
    return $(selector).length;

if (exists(selector)) {
    // do something

It's very minimal and saves you having to enclose the selector with $() every time.

share|improve this answer
I like this approach –  Akmur Mar 18 at 14:13
if ( $('#myDiv').size() > 0 ) { //do something }

size() counts the number of elements returned by the selector

share|improve this answer
@Furbeenator I don't know where you get your information from, but .size() does nothing more than return .length. There's a reason it's deprecated –  Ian Jun 3 '13 at 21:41
You are correct, but calling .length, being a property, requires slightly less overhead than a function call to .size(). My bad. –  Furbeenator Jun 5 '13 at 18:30

I'm using this:

    $.fn.ifExists = function(fn) {
      if (this.length) {

Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/

share|improve this answer

Is $.contains() what you want?

jQuery.contains( container, contained )

The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

share|improve this answer
NOW it is an answer –  mplungjan Dec 17 '13 at 8:49

i always use

if ( $(selector)[0] ){}

thats nice and short

share|improve this answer

The reason all of the previous answers require the .length parameter is that they are mostly using jquery's $() selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for all matches to that selector and populating an array with them.

The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use document.querySelector(selector) instead, because it returns the first element it matches or null if not found.

function elementIfExists(selector){  //named this way on purpose, see below
    return document.querySelector(selector);
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;

However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).

var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
console.log(elementIfExists("#myid")); /* null */
console.log(myel); /* giant table lingering around detached from document */
myel=null; /* now it can be garbage collected */

In some cases this may be desired. It can be used in a for loop like this:

/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
    if (myel == myblacklistedel) break;

If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?

function elementExists(selector){
    return !!document.querySelector(selector);
/* usage: */
var hastables = elementExists("table");  /* will be true or false */
if (hastables){
    /* insert css style sheet for our pretty tables */
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
                           alert("bad table layouts");},3000);
share|improve this answer

In JavaScript you can do it this way :

if(document.querySelectorAll('*')!=null) { // It exists }

share|improve this answer

I stumbled upon this question and i'd like to share a snippet of code i currently use:

$.fn.exists = function(callback) {
    var self = this;
    var wrapper = (function(){
            function notExists () {}

            notExists.prototype.else = function(fallback){
                if (!self.length) {                    

            return new notExists;

    if(self.length) {

    return wrapper;

And now i can write code like this -

    alert ("it exists");
    alert ("it doesn't exist");

What's more exciting about this stuff is how it's written in CoffeeScript:

$.fn.exists = (callback) ->
    exists = @length
    callback.call() if exists        
    new class
       else: (fallback) ->            
            fallback.call() if not exists
share|improve this answer
I find OP's original approach not only to be much more minimal but more elegant than this. Seems like overkill to write this much code when OP's method is shorter, and doesn't involve callbacks. –  Lev Aug 5 at 7:31
For simple cases - you're right. But for more complex situations involving a lot of code on both cases i think my approach is better. –  Eternal1 Aug 5 at 7:38
else as a property name will fail in some older browsers. –  cookie monster Aug 14 at 17:34

protected by Andrew Barber Apr 8 '13 at 3:55


Would you like to answer one of these unanswered questions instead?
