518

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

1

11 Answers 11

806

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

Sign up to request clarification or add additional context in comments.

13 Comments

what is the point in this when .length does exactly the same?
This is one of the sillier plugins I've ever seen...
I have reworded the reply to emphasize that $.fn.exists is slower.
@TrueBlueAussie it is very bad API design to have a "exists" function that can return 3, IMO!
@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! :)
|
102

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

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

1 Comment

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 :)
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)) { } 

2 Comments

Could you provide an example where chaining is not possible?
@TomasM: Well, .exist() returns a bool, on which you cannot call jQuery methods, see comments below this answer.
16

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.

1 Comment

Note: The question has been changed to mean what they intended after this was posted, so this answer no longer has meaning here :)
16
if ($('#elem')[0]) { // do stuff } 

2 Comments

I like this for brevity. Can anyone say whether it will work everywhere .length will work?
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.
15

Yet another way:

$('#elem').each(function(){ // do stuff }); 

3 Comments

Nice, cleaner approach if you don't want to do anything special if #elem does not exist.
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 :)
I can't believe that this answer get upvotes. This have nothing to do with existens check. Totaly wrong direction.
3

Alternatively:

if( jQuery('#elem').get(0) ) {} 

1 Comment

This is no shorter than .length (and slower). $('#elem')[0] would do the same.
2
jQuery.fn.exists = function(selector, callback) { var $this = $(this); $this.each(function() { callback.call(this, ($(this).find(selector).length > 0)); }); }; 

1 Comment

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

2 Comments

sounds like a lot of effort, compared to just reading an existing property
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.
-4

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

if ($("#elem").index() ! = -1) {} 

2 Comments

you have to create the exists() function
This is longer and slower than using .length. This answer is best deleted (voting to delete).
-7

firstly create a function:

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

then

if($(selector).is_exists()){ ... } 

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.