510

In Mootools, I'd just run if ($('target')) { ... }. Does if ($('#target')) { ... } in jQuery work the same way?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
One Crayon
  • 19,119
  • 11
  • 33
  • 40
  • 1
    See also [Is there an `exists` function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – Bergi Aug 02 '13 at 14:08

11 Answers11

796

As the other commenters are suggesting the most efficient way to do it seems to be:

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

If you absolutely must have an exists() function - which will be slower- you can do:

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

Then in your code you can use

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

As answered here

Community
  • 1
  • 1
Pat
  • 36,282
  • 18
  • 72
  • 87
  • 1
    what is the point in this when .length does exactly the same? – redsquare May 27 '10 at 03:19
  • 7
    This is one of the sillier plugins I've ever seen... – Alex Sexton May 27 '10 at 04:26
  • 8
    I have reworded the reply to emphasize that $.fn.exists is slower. – Pat May 31 '10 at 14:58
  • It's funny that @snover makes the exact same comment here that he does in the linked answer. Didn't get the point across the first time? – Steven Jul 25 '11 at 22:43
  • @Stevus I don't understand your question... snover and others saw two answers that were not good enough, they commented on both (two years after the answers were posted)... I saw the comments and updated my answer to take them into consideration. Which part of the sequence of events is bothering you? – Pat Jul 28 '11 at 15:58
  • 1
    I guess the example of .exists is relevant. I think the author wanted to show that you can design an exists function that could for example return true only if the length is greater than 3. So I don't think more information is anyhow silly... – Etienne Noël Nov 09 '12 at 14:14
  • other link: [learn jquery](http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/) – Robin Gomez Sep 24 '14 at 20:26
  • Good answer, but why `this.length>0` rather than just `this.length` in the exists() function? – iCollect.it Ltd Jul 17 '15 at 16:34
  • 1
    @TrueBlueAussie so it returns a bool and not a number – Josef Sep 15 '15 at 13:02
  • @Josef: a zero, or non-zero, number evaluates to a boolean when tested using if. As I said, it is *not* required here. :P – iCollect.it Ltd Sep 15 '15 at 13:06
  • 1
    @TrueBlueAussie it is very bad API design to have a "exists" function that can return 3, IMO! – Josef Sep 15 '15 at 13:24
  • 3
    @Josef: And very poor code design if you are doing math on the return value of a function called `exists`... IMHO :) Actually adding a one-liner extension, like `exists()` that is 2 characters *longer* than what it replaces is silly to begin with for JS! :) – iCollect.it Ltd Sep 15 '15 at 13:26
  • @TrueBlueAussie for JS that is true. (I do more with C++ where this makes sense imo) The problem with an API that has such quirks is, that **someone** will do math on the result of `exists` and when the API is fixed, things break. – Josef Sep 15 '15 at 14:11
99

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • 1
    This is more practical than the accepted answer's second suggestion. (Why would you introduce a slower & *longer* alternative to simply checking length!). I also note your answer was earlier +1 :) – iCollect.it Ltd Sep 15 '15 at 13:31
22

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)) { }
Jon Erickson
  • 112,242
  • 44
  • 136
  • 174
  • 1
    Could you provide an example where chaining is not possible? – Tomas M Aug 01 '15 at 17:21
  • @TomasM: Well, `.exist()` returns a bool, on which you cannot call jQuery methods, see comments below [this answer](http://stackoverflow.com/a/444403/3821804). – GingerPlusPlus Oct 30 '15 at 16:35
17

I think most of the people replying here didn't quite understand the question, or else I might be mistaken.

The question is "how to check whether or not a selector exists in jQuery."

Most people have taken this for "how to check whether an element exists in the DOM using jQuery." Hardly interchangeable.

jQuery allows you to create custom selectors, but see here what happens when you try to use on e before initializing it;

$(':YEAH');
"Syntax error, unrecognized expression: YEAH"

After running into this, I realized it was simply a matter of checking

if ($.expr[':']['YEAH']) {
    // Query for your :YEAH selector with ease of mind.
}

Cheers.

skqr
  • 703
  • 7
  • 8
  • 4
    Note: The question has been changed to mean what they intended after this was posted, so this answer no longer has meaning here :) – iCollect.it Ltd Jul 17 '15 at 16:25
16
if ($('#elem')[0]) {
  // do stuff
}
Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
Sean Curtis
  • 161
  • 1
  • 2
  • I like this for brevity. Can anyone say whether it will work everywhere .length will work? – Sam Hasler Nov 14 '11 at 12:06
  • 1
    The only case it wouldn't is if jQuery gave you an array with e.g. null (or otherwise "falsy") contents instead of DOM element objects, which would be surprising. – natevw Feb 28 '15 at 00:38
16

Yet another way:

$('#elem').each(function(){
  // do stuff
});
PhilT
  • 4,166
  • 1
  • 36
  • 26
  • 4
    Nice, cleaner approach if you don't want to do anything special if #elem does not exist. – Abdullah Jibaly Feb 09 '11 at 17:09
  • As an ID can only exists once, and duplicates are ignored by JS and jQuery, this may lead to confusion if you do not explain that it is a 0 or 1 situation :) – iCollect.it Ltd Jul 17 '15 at 16:22
  • I can't believe that this answer get upvotes. This have nothing to do with existens check. Totaly wrong direction. – Mike Aron Jul 26 '18 at 19:34
3

Alternatively:

if( jQuery('#elem').get(0) ) {}
James
  • 109,676
  • 31
  • 162
  • 175
2
jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};
Taryn
  • 242,637
  • 56
  • 362
  • 405
logrox
  • 53
  • 5
  • 1
    Why would you ever do an `each` *and a callback* if you just want to know if there was zero or more matches? I now feel more stupid than I was before I read this! -1. – iCollect.it Ltd Jul 17 '15 at 16:42
1

I prefer the

    if (jQuery("#anyElement").is("*")){...}

Which basically checks if this elements is a kind of "*" (any element). Just a cleaner syntax and the "is" makes more sense inside an "if"

user1134422
  • 1,161
  • 8
  • 7
  • 3
    sounds like a lot of effort, compared to just reading an existing property – Christophe Jan 15 '13 at 22:03
  • This is significantly slower than the alternatives and arguably less readable. You would not introduce parsing to check the length of an array and a jQuery object behaves just like an array. – iCollect.it Ltd Jul 17 '15 at 16:31
-3

For me .exists doesn't work, so I use the index :

if ($("#elem").index() ! = -1) {}
Aliaksei Kliuchnikau
  • 13,589
  • 4
  • 59
  • 72
-6

firstly create a function:

$.fn.is_exists = function(){ return document.getElementById(selector) }

then

if($(selector).is_exists()){ ... }
Zsolt Takács
  • 368
  • 4
  • 14
  • 4
    This presumes the selector was an ID, not a jQuery selector as required. Best delete this answer as it is misleading. -1 & voting to delete – iCollect.it Ltd Jul 17 '15 at 16:26