2910

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 a more elegant way to approach this? Perhaps a plugin or a function?

René
  • 5,285
  • 3
  • 20
  • 37
Jake McGraw
  • 52,590
  • 10
  • 46
  • 62

44 Answers44

2599

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

if ($(selector).length)

You don't need that >0 part.

MartinNajemi
  • 25
  • 1
  • 5
Tim Büthe
  • 58,799
  • 16
  • 82
  • 126
  • 56
    @abhirathore2006 If you use an id selector and the element doesn't exist then length is 0 and doesn't throw exceptions. – Robert Jun 29 '17 at 20:35
  • 17
    Interestingly enough `NaN != false`. – Robert Jun 29 '17 at 20:52
  • 16
    @James That's because `[].toString() === [].join(',') === ""` and `"" === ""`. – Ismael Miguel Jul 08 '17 at 22:09
  • 1
    `[].toString() == ""` is true, `[].join(',') == ""` is also true, `[].toString() == [].join(',')` again true, `[].toString() == "" && [].join(',') == ""` still true, but `[].toString() == [].join(',') == ""` is false... I don't really understand, why the last one is false, when all previous are true. – debute Aug 09 '17 at 13:54
  • 3
    @debute the last one probably compares `true` (the boolean result of the first `==` ) with `""`, which is `false`. I.e.: `[].toString() == [].join(',') == ""` -> `true == ""` -> `false` – Sebastianb Aug 25 '17 at 14:46
  • 8
    @Robert and `typeof NaN == 'number'` – oriadam Jan 31 '18 at 11:06
  • 4
    Is there a tangible benefit to not including the `> 0` part? Seems clearer to me that way. – Sinjai Feb 14 '18 at 05:09
  • 2
    @Sinjai once you get used to programming a bit you will ask yourself if there is a tangible benefit to including the > 0. Because it's very clear without it and fully legit. – jox Nov 08 '20 at 16:15
  • @jox I come from the land of relative sanity (not JavaScriptLand) where we still value semantics. Checking if an element exists is not the same as checking if an element has a length which is not the same as checking if the length is greater than 0. JS can keep its hacks. The costly part is maintaining the code, not writing it. – Sinjai Nov 09 '20 at 18:13
  • @Sinjai I'm also not from JavaScriptLand. :-) But I happen to travel it. I came around quite a bit in the Universe. Asking a non-boolean if it's truthy or falsy is a common idiom that's used not only in JavaScriptLand. Even in C you can (and happily do (well maybe not you ;-) )) ask integers if they are not zero without any operator (e.g. `if (x) {}`). And it's usually other things that make code hard to maintain. No offense, all good. Everybody has their preferences. – jox Nov 10 '20 at 00:45
  • @jox You're right, it's the truthy/falsey concept that is to blame here. I guess my distaste is really with that. But given the fact that it's a thing, I like to try to be as clear as possible. I realize the industry as a whole may well disagree with me, though that brings a tear to my eye. – Sinjai Nov 12 '20 at 16:24
  • Wouldn't `$(selector).first().length` be a little more efficient? Otherwise, if there are a ton of matches, jQuery will build an object containing all matches even though we only need one or none. – Cerin Nov 18 '20 at 00:31
  • @Cerin hmm, I would think the object is built when `$(...)` is executed. Only afterwards you check either the length property or invoke `.first()`, so it doesn't stop the actual search after the first one, right? – Tim Büthe Nov 18 '20 at 07:46
  • @TimBüthe That's a good point. Then perhaps incorporating `first` into the selector itself would be better? Like `$(':first').length`? – Cerin Nov 18 '20 at 12:50
1386

Yes!

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

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

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

Jake McGraw
  • 52,590
  • 10
  • 46
  • 62
  • 255
    I just write: if( $(selector).length ){ ... } without the '> 0' – vsync Nov 24 '09 at 09:22
  • 370
    Your `$.fn.exists` example is 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 04:14
  • 213
    @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 02 '10 at 20:52
  • 48
    @quixoto, sorry but .length is a standard across many languages that does not need wrapping. How else do you interpret .length? – redsquare Aug 03 '10 at 00:13
  • 145
    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 03 '10 at 00:29
  • 3
    What a terrible answer. What if selector matches hundreds of nodes and the first one `exists`? It should bail and return true immediately. No point in bothering with the rest of it. example: `if( $('div.tag:contains("nsfw")').exist() ) agecheck();` on an imageboard or something – KitsuneYMG Mar 05 '14 at 19:27
  • 12
    "Some people, when confronted with a problem, think 'I know, I'll extend the base library.' Now they have two problems." Once you've defined this function and start using `.exists()` everywhere, all of that code becomes unportable in the absence of such a function definition. Sounds like this would reduce maintainability. – cowbert Jun 01 '15 at 09:06
  • 5
    Great answer...but try any number, for example: $(666).exists() //the result is true (wrong) – earnaz Sep 16 '15 at 16:19
  • 2
    A `jQuery` collection will "exist", whether it is empty or not. You wouldn't feel the need to `Array.prototype.exists = function() {return this.length;}` for code readability. – AndFisher Aug 24 '17 at 11:39
385

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 */ }
R3tep
  • 11,061
  • 9
  • 38
  • 69
Jon Erickson
  • 102,662
  • 42
  • 131
  • 170
  • 12
    The first method reads better. $("a").exists() reads as "if elements exist." $.exists("a") reads as "if there exists elements." – strager Jan 14 '09 at 20:00
  • 17
    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 00:31
  • 21
    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 05:42
  • 40
    Why on earth would you need to chain this? `$(".missing").css("color", "red")` already does the right thing… (i.e. nothing) – Ben Blank Sep 08 '10 at 06:43
  • 1
    First example ($('.mySelector').length) works fine, no need to create an exists() wrapper for it. – nickb Sep 14 '10 at 19:16
  • The 2nd edit.... if ( $('#myDiv')[0] ) {..... undefined index 0. You should not compare the result direct, since there is NO result. Instead you should.... if ( typeof $('#myDiv')[0] !='undefined' )... – Christian Sep 17 '10 at 07:18
  • 19
    The stuff about chaining is complete tosh - there are _plenty_ of jQuery `$.fn` methods that return something other than a new jQuery object and therefore don't chain. – Alnitak Jul 18 '14 at 08:12
  • `$("
    ").length > 0` would return true, giving the impression that the selector used exist, but it is in fact just a valid HTML string. To avoid that, `$.find(selector).length > 0` would throw an error on invalid selector expression.
    – Emile Bergeron Oct 08 '16 at 00:48
142

You can use this:

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

// if element does not exist
if(!$('selector').length){ /* do something */ }
Derek 朕會功夫
  • 84,678
  • 41
  • 166
  • 228
Yanni
  • 2,469
  • 2
  • 18
  • 7
110

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).

Randika Vishman
  • 7,157
  • 3
  • 55
  • 75
Magne
  • 14,749
  • 8
  • 57
  • 77
  • 59
    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 07 '12 at 16:30
  • 7
    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 08:55
  • 1
    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 03:04
  • 1
    Maybe something like `if('#foo a.special')[0])` if you still wanted to use jQuery selectors? Though, I guess that kind of defeats the purpose. – Noz May 27 '13 at 20:21
  • Even when you wrote this in 2012, the *arguments of speed* did not stand due to change in *standards of technology*. The argument of *speed* in JavaScript Engines has been dead for years now. – SpYk3HH Oct 02 '13 at 17:26
  • 30
    @Noz `if(document.querySelector("#foo a.special"))` would work. No jQuery needed. – Blue Skies Dec 08 '13 at 00:43
  • 35
    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 08 '13 at 00:45
  • 24
    Remember the good old days when document.getElementById was all we had? And I always forgot the document. and couldn't figure out why it didn't work. And I always spelled it wrong and got the character casing wrong. – JustJohn Nov 18 '14 at 21:05
  • 3
    I would quit writing JavaScript if I had to: 1) work without debug console or 2) work with `getElementById` – AGamePlayer Mar 05 '16 at 03:33
  • 2
    Obviously the vanilla JS methods are faster, but note that the question didn't specify selection by element id, so really you need `document.querySelector()`, and even that can't handle all of the selectors that jQuery can. So while calling a single, native JS function for this purpose is *good*, in some cases you'd have to write extra code. (Also, `if ($(selector).length)` is pretty self-explanatory - I really don't think it would confuse anyone with any JS experience.) – nnnnnn Jul 08 '16 at 03:31
  • 3
    Good luck testing `:visible`, or any of other custom jquery selectors – eithed Aug 23 '16 at 15:59
78

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.

Salman A
  • 229,425
  • 77
  • 398
  • 489
  • 1
    I came here to post this exact answer... obligatory fiddle: http://jsfiddle.net/jasonwilczak/ekjj80gy/2/ – JasonWilczak Mar 25 '15 at 15:08
  • 3
    @JasonWilczak Care to comment why not instead: .eq[0] or .first() to refer to a first element found rather than type casting? – Jean Paul A.K.A el_vete Jul 21 '15 at 13:51
  • 5
    No, `jQuery.first()` or `jQuery.eq(0)` both return objects, objects are truthy even if they are empty-ish. This example should illustrate why these functions cannot be used as-is: `if(jQuery("#does-not-exist").eq(0)) alert("#does-not-exist exists")` – Salman A Jul 21 '15 at 15:16
  • 1
    Correct. `.eq(0)` returns just another jQuery object truncated to length 1 or 0. `.first()` is just a convenience method for `.eq(0)`. But `.get(0)` returns the first DOM element or `undefined` and is the same as `[0]`. The first DOM element in a jQuery object is stored in the regular object property with the name `'0'`. That's a simple property access. The only type casting stems from the implicit conversion of the number `0` to the string `'0'`. So if type casting is a problem you could use `$.find(selector)['0']` instead. – Robert Jun 29 '17 at 20:20
71

You can use:

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

A little more elegant, perhaps.

Devon
  • 5,670
  • 4
  • 36
  • 45
  • 38
    This is too much for such a simple thing. see Tim Büthe answer – vsync Nov 24 '09 at 09:28
  • This is the correct answer. The 'length' method has the problem that it gives false positive with any number, for example: $(666).length // returns 1, but it's not a valid selector – earnaz Sep 16 '15 at 16:23
  • 1
    This is extremely expensive for very simple task. Just look into jquery implementation if .is() and you will see how much code it needs to process to answer you this simple question. Also it is not obvious what you want to do exactly, so it is same or maybe less elegant then solution in question. – micropro.cz Feb 22 '16 at 19:59
  • 1
    @earnaz great point, nice catch. I don't see where that's actually a worthwhile concern, though. Devs identifying elements with `666` probably have plenty of other reasons their code's broken. While it is an invalid selector, $(666).length *is valid javascript*: It evaluates to truthy, and therefore *should* satisfy the condition. – Todd Mar 08 '16 at 12:55
  • @earnaz to avoid that specific case, `$.find(666).length` works. – Emile Bergeron Oct 08 '16 at 00:41
70

This plugin can be used in an if statement like if ($(ele).exist()) { /* DO WORK */ } or using a callback.

Plugin

;;(function($) {
    if (!$.exist) {
        $.extend({
            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];
                                break;
                            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]);
                                    }
                                }
                                break;
                            case 'string':
                                ele = $(arguments[x]);
                                break;
                        }
                    }
                }

                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 {
                    if (ele.length <= 1) return ele.length > 0 ? true : false;
                    else return ele.length;
                }

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

jsFiddle

You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does not exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does not exist. Of course, if it does exist, the first function will fire and the chain will continue.

Keep in mind that using the callback variant helps maintain chainability – 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    */
    /*    This will ONLY fire if the element 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    */
    }
})
Palec
  • 10,298
  • 7
  • 52
  • 116
SpYk3HH
  • 21,364
  • 10
  • 64
  • 79
68

I see most of the answers here are not accurate as they should be, they check element length, it can be OK in many cases, but not 100%, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:

$.fn.exists = $.fn.exists || function() { 
  return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); 
}

This will check both length and type, Now you can check it this way:

$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true
Alireza
  • 83,698
  • 19
  • 241
  • 152
58

You could use this:

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something*/}
Bellash
  • 5,719
  • 3
  • 39
  • 72
Amitābha
  • 3,261
  • 4
  • 33
  • 55
58

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...

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
amypellegrini
  • 1,026
  • 9
  • 13
  • 5
    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
46

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
myel.getParentNode.removeChild(myel);
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);
technosaurus
  • 7,101
  • 1
  • 28
  • 49
44

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.

Community
  • 1
  • 1
hiway
  • 3,722
  • 10
  • 31
  • 51
  • 3
    This doesn't accept a selector, which means he would have to select it, which means he could just check the result of his selection. –  Jun 04 '16 at 13:28
44

You can check element is present or not using length in java script. If length is greater than zero then element is present if length is zero then element is not present

// These by Id
if ($("#elementid").length > 0) {
  // Element is Present
} else {
  // Element is not Present
}

// These by Class
if ($(".elementClass").length > 0) {
  // Element is Present
} else {
  // Element is not Present
}
ROOT
  • 10,339
  • 5
  • 24
  • 40
Anurag Deokar
  • 820
  • 7
  • 13
42

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
Oleg
  • 8,818
  • 2
  • 40
  • 55
  • 12
    How often do you find yourself calling `$()` with an empty object as an argument? – nnnnnn Dec 22 '14 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 '14 at 15:03
  • 3
    Why on earth would you pass an empty object `{}` to `$()`? – All Workers Are Essential Mar 26 '15 at 15:46
  • 8
    @cpburnz why do you ask me? I was just an API provider... People pass all kinds of stupid things to APIs. – Oleg Mar 26 '15 at 15:48
  • 4
    Just noticed, the jquery issue thread that @FagnerBrack referenced was updated shortly after his comment; it looks like it's not going away after all. – Joseph Gabriel Apr 18 '16 at 21:09
37

Checking for existence of an element is documented neatly in the official jQuery website itself!

Use the .length property of the jQuery collection returned by your selector:

if ($("#myDiv").length) {
    $("#myDiv").show();
}

Note that it isn't always necessary to test whether an element exists. The following code will show the element if it exists, and do nothing (with no errors) if it does not:

$("#myDiv").show();
Palec
  • 10,298
  • 7
  • 52
  • 116
Tilak Maddy
  • 3,027
  • 2
  • 26
  • 44
33

this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:

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

if ($(selector).exists()) {
    // the element exists, now what?...
}
Santiago Hernández
  • 4,513
  • 1
  • 23
  • 33
29
$(selector).length && //Do something
SJG
  • 1,723
  • 1
  • 15
  • 10
28

Try testing for DOM element

if (!!$(selector)[0]) // do stuff
guest271314
  • 1
  • 10
  • 82
  • 156
28

Inspired by hiway's answer I came up with the following:

$.fn.exists = function() {
    return $.contains( document.documentElement, this[0] );
}

jQuery.contains takes two DOM elements and checks whether the first one contains the second one.

Using document.documentElement as the first argument fulfills the semantics of the exists method when we want to apply it solely to check the existence of an element in the current document.

Below, I've put together a snippet that compares jQuery.exists() against the $(sel)[0] and $(sel).length approaches which both return truthy values for $(4) while $(4).exists() returns false. In the context of checking for existence of an element in the DOM this seems to be the desired result.

$.fn.exists = function() {
    return $.contains(document.documentElement, this[0]); 
  }
  
  var testFuncs = [
    function(jq) { return !!jq[0]; },
    function(jq) { return !!jq.length; },
    function(jq) { return jq.exists(); },
  ];
    
  var inputs = [
    ["$()",$()],
    ["$(4)",$(4)],
    ["$('#idoexist')",$('#idoexist')],
    ["$('#idontexist')",$('#idontexist')]
  ];
  
  for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
    input = inputs[i][1];
    tr = "<tr><td>" + inputs[i][0] + "</td><td>"
          + testFuncs[0](input) + "</td><td>"
          + testFuncs[1](input) + "</td><td>"
          + testFuncs[2](input) + "</td></tr>";
    $("table").append(tr);
  }
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
  <td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
  
  $.fn.exists = function() {
    return $.contains(document.documentElement, this[0]); 
  }
  
</script>
Community
  • 1
  • 1
Oliver
  • 8,258
  • 7
  • 64
  • 94
28

No need for jQuery (basic solution)

if(document.querySelector('.a-class')) {
  // do something
}

Much more performant option below(notice lack of a dot before a-class).

if(document.getElementsByClassName('a-class')[0]) {
  // do something
}

querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to jsperf https://jsperf.com/getelementsbyclassname-vs-queryselectorall/25

Pawel
  • 10,190
  • 4
  • 56
  • 60
26

I just like to use plain vanilla javascript to do this.

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}
24

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.otherwise = function(fallback){
                if (!self.length) {                    
                    fallback.call();
                }
            };

            return new notExists;
        })();

    if(self.length) {
        callback.call();    
    }

    return wrapper;
}

And now i can write code like this -

$("#elem").exists(function(){
    alert ("it exists");
}).otherwise(function(){
    alert ("it doesn't exist");
});

It might seem a lot of code, but when written in CoffeeScript it is quite small:

$.fn.exists = (callback) ->
    exists = @length
    callback.call() if exists        
    new class
       otherwise: (fallback) ->            
            fallback.call() if not exists
Eternal1
  • 4,917
  • 1
  • 27
  • 43
  • 9
    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 05 '14 at 07: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 05 '14 at 07:38
  • 4
    In what complex situation would this approach be better than a simple if/else statement? – Jarvl Jun 24 '16 at 18:55
20

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;
};
jcreamer898
  • 7,809
  • 4
  • 39
  • 55
19

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.

MAXIM
  • 4,662
  • 15
  • 78
  • 125
  • 3
    This reads as "if exists thing" instead of "if thing exists" which `if($("#thing").exists(){}` reads as. Also, it's not the jQuery way. – 1j01 Jun 21 '15 at 21:48
16

I'm using this:

    $.fn.ifExists = function(fn) {
      if (this.length) {
        $(fn(this));
      }
    };
    $("#element").ifExists( 
      function($this){
        $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});               
      }
    ); 

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

andy_314
  • 425
  • 4
  • 16
16

$("selector") returns an object which has the length property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript 0 == false, so if you don't get 0 your code will run.

if($("selector").length){
   //code in the case
} 
Hydrothermal
  • 3,988
  • 7
  • 22
  • 43
Kamuran Sönecek
  • 3,088
  • 2
  • 24
  • 49
  • 5
    "give an array" — No, it doesn't. It gives you a jQuery object (which shares some properties with an array). Your answer is essentially the same as Tim Büthe's from 2009 too. – Quentin Apr 27 '16 at 12:33
15

Here is my favorite exist method in jQuery

$.fn.exist = function(callback) {
    return $(this).each(function () {
        var target = $(this);

        if (this.length > 0 && typeof callback === 'function') {
            callback.call(target);
        }
    });
};

and other version which supports callback when selector does not exist

$.fn.exist = function(onExist, onNotExist) {
    return $(this).each(function() {
        var target = $(this);

        if (this.length > 0) {
            if (typeof onExist === 'function') {
                onExist.call(target);
            }
        } else {
            if (typeof onNotExist === 'function') {
                onNotExist.call(target);
            }
        }
    });
};

Example:

$('#foo .bar').exist(
    function () {
        // Stuff when '#foo .bar' exists
    },
    function () {
        // Stuff when '#foo .bar' does not exist
    }
);
ducdhm
  • 1,899
  • 14
  • 24
15

You don't have to check if it's greater than 0 like $(selector).length > 0, $(selector).length it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}
Community
  • 1
  • 1
Andrei Todorut
  • 3,393
  • 1
  • 14
  • 23
13

Here is the complete example of different situations and way to check if element exists using direct if on jQuery selector may or may not work because it returns array or elements.

var a = null;

var b = []

var c = undefined ;

if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}
// output: a doesn't exit

if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}
// output: b exist

if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}
// output: c doesn't exit

FINAL SOLUTION

if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist

if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
    //output : xusyxxs doesnn't exist

Demo

console.log("existing id", $('#id-1').length)
console.log("non existing id", $('#id-2').length)

console.log("existing class single instance", $('.cls-1').length)
console.log("existing class multiple instance", $('.cls-2').length)
console.log("non existing class", $('.cls-3').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id-1">
  <div class="cls-1 cls-2"></div>
  <div class="cls-2"></div>
</div>
abhirathore2006
  • 2,807
  • 22
  • 29
  • You can try $("#xysyxxs") in your debugger, you'll see that jquery doesn't return null or undefined. So the final solution would not work – Béranger Sep 09 '16 at 12:27
11

Yes The best method of doing this :

By JQuery :

if($("selector").length){
   //code in the case
}

selector can be Element ID OR Element Class

OR

If you don't want to use jQuery Library then you can achieve this by using Core JavaScript :

By JavaScript :

if(document.getElementById("ElementID")) {
    //Do something...
}
Sunil Kumar
  • 2,655
  • 1
  • 16
  • 30
11

Try this.

simple and short and usable in the whole project:

jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin

Usage:

console.log($("element-selector").exists());

_________________________________

OR EVEN SHORTER: (for when you don't want to define a jQuery plugin):

if(!!$("elem-selector")[0]) ...;

or even

if($("elem-selector")[0]) ...;
Hassan Sadeghi
  • 1,276
  • 2
  • 5
  • 13
11
if ( $('#myDiv').size() > 0 ) { //do something }

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

sth
  • 200,334
  • 49
  • 262
  • 354
  • 11
    @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 03 '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 05 '13 at 18:30
5

A simple utility function for both id and class selector.

function exist(IdOrClassName, IsId) {
  var elementExit = false;
  if (IsId) {
    elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
  } else {
    elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
  }
  return elementExit;
}

calling this function like bellow

$(document).ready(function() {
  $("#btnCheck").click(function() {
    //address is the id so IsId is true. if address is class then need to set IsId false
    if (exist("address", true)) {
      alert("exist");
    } else {
      alert("not exist");
    }
  });
});
ROOT
  • 10,339
  • 5
  • 24
  • 40
sina_Islam
  • 669
  • 7
  • 14
5

Just check the length of the selector, if it more than 0 then it's return true otherwise false.

For ID:

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}

For Class:

 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

For Dropdown:

if( $('#selector option').size() ) {   // use this if you are using dropdown size to check

   // it exists
}
Majedur Rahaman
  • 1,582
  • 17
  • 28
4

All answers is not working bullet proof to check existence of an element in jQuery. After many years of coding, only this solution does not throw any warnings about existance or not:

if($(selector).get(0)) { // Do stuff }

Or to bail instead in the beginning of your function:

if(!$(selector).get(0)) return;

Explained

In this case, you dont have to deal with zero | null lengths issues. This forces to fetch an element, not count them.

Jonas Lundman
  • 1,022
  • 11
  • 15
4

I am using this:

 if($("#element").length > 0){
   //the element exists in the page, you can do the rest....
 }

Its very simple and easy to find an element.

ROOT
  • 10,339
  • 5
  • 24
  • 40
Abdul Rahman
  • 1,399
  • 2
  • 17
  • 35
  • 2
    Your answer adds no new information to what's already been posted. This is merely a subset of the information in [the accepted answer](https://stackoverflow.com/a/587408/3303195). – faintsignal Jan 11 '19 at 23:07
1

With jQuery you do not need >0, this is all you need:

if ($(selector).length)

With vanilla JS, you can do the same with:

if(document.querySelector(selector))

If you want to turn it into a function that returns bool:

const exists = selector => !!document.querySelector(selector);

if(exists(selector)){
  // some code
}
chickens
  • 9,225
  • 4
  • 38
  • 41
0

By default - No.

There's the length property that is commonly used for the same result in the following way:

if ($(selector).length)

Here, 'selector' is to be replaced by the actual selector you are interested to find if it exists or not. If it does exist, the length property will output an integer more than 0 and hence the if statement will become true and hence execute the if block. If it doesn't, it will output the integer '0' and hence the if block won't get executed.

Amit Sharma
  • 314
  • 2
  • 15
  • of course there are other elegant ways to get the same result but this is one of the simplest and most effective – Amit Sharma Mar 11 '20 at 05:09
0

I found that this is the most jQuery way, IMHO. Extending the default function is easy and can be done in a global extension file.

$.fn.exist = function(){
  return !!this.length;
};

console.log($("#yes").exist())

console.log($("#no").exist())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="yes">id = yes</div>
Greedo
  • 2,906
  • 1
  • 8
  • 22
0

There is an oddity known as short circuit conditioning. Not many are making this feature known so allow me to explain! <3

//you can check if it isnt defined or if its falsy by using OR
console.log( $(selector) || 'this value doesnt exist' )

//or run the selector if its true, and ONLY true
console.log( $(selector) && 'this selector is defined, now lemme do somethin!' )

//sometimes I do the following, and see how similar it is to SWITCH
console.log(
({  //return something only if its in the method name
    'string':'THIS is a string',
    'function':'THIS is a function',
    'number':'THIS is a number',
    'boolean':'THIS is a boolean'
})[typeof $(selector)]||
//skips to this value if object above is undefined
'typeof THIS is not defined in your search')

The last bit allows me to see what kind of input my typeof has, and runs in that list. If there is a value outside of my list, I use the OR (||) operator to skip and nullify. This has the same performance as a Switch Case and is considered somewhat concise. Test Performance of the conditionals and uses of logical operators.

Side note: The Object-Function kinda has to be rewritten >.<' But this test I built was made to look into concise and expressive conditioning.

Resources: Logical AND (with short circuit evaluation)

Gareth Compton
  • 139
  • 1
  • 10
  • Not many are using this feature because it makes the code harder to read and to maintain. Also, be careful the last part is not similar to a switch because _all_ expressions are executed rather than only the one you care for. – bfontaine Mar 18 '21 at 17:01
-1

Use the following syntax to check if the element actually exists using jQuery.

let oElement = $(".myElementClass");
if(oElement[0]) {
    // Do some jQuery operation here using oElement
}
else {
    // Unable to fetch the object
}
Emile Bergeron
  • 14,368
  • 4
  • 66
  • 111
Jonathan Cardoz
  • 636
  • 7
  • 8
-1

The input won't have a value if it doesn't exist. Try this...

if($(selector).val())
Manish Vadher
  • 1,208
  • 12
  • 14
-3

Use querySelectorAll with forEach, no need for if and extra assignment:

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

as the opposite to:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}
Rafal Enden
  • 2,317
  • 1
  • 16
  • 13