By Jake McGraw


2008-08-27 19:49:41 8 Comments

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?

30 comments

@Hassan Sadeghi 2018-08-18 06:27:02

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 2018-08-23 17:09:03

Why down vote?? try and then vote. Some people will quickly DownVote when they do not understand themselves! but i don't remove my answer to using by another programmers. I always use this method and it is absolutely correct.

@Andrew Grothe 2018-12-11 13:44:56

Works quite well actually. I would recommend naming it simply "exists" as "isExists" is grammatically.... weird :). I like short and sweet.

@Magne 2012-01-11 12:27:49

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

@kikito 2012-03-07 16:30:49

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.

@Magne 2012-05-10 08:55:38

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.

@PerryCS 2013-02-10 03:04:13

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.

@Noz 2013-05-27 20:21:43

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.

@SpYk3HH 2013-10-02 17:26:58

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.

@Blue Skies 2013-12-08 00:43:53

@Noz if(document.querySelector("#foo a.special")) would work. No jQuery needed.

@Blue Skies 2013-12-08 00:45:52

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.

@JustJohn 2014-11-18 21:05:44

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.

@AGamePlayer 2016-03-05 03:33:32

I would quit writing JavaScript if I had to: 1) work without debug console or 2) work with getElementById

@nnnnnn 2016-07-08 03:31:53

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

@eithed 2016-08-23 15:59:33

Good luck testing :visible, or any of other custom jquery selectors

@Alireza 2017-05-20 09:21:12

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

@Kamuran Sönecek 2016-03-25 11:05:49

$("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
} 

@Quentin 2016-04-27 12:33:17

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

@Majedur Rahaman 2018-12-20 08:38:46

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
}

@Abdul Rahman 2018-12-19 04:30:54

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.

@faintsignal 2019-01-11 23:07:56

Your answer adds no new information to what's already been posted. This is merely a subset of the information in the accepted answer.

@hiway 2013-10-23 05:46:50

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.

@user1106925 2016-06-04 13:28:17

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.

@Rafal Enden 2018-08-23 16:22:24

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');
}

@Manish Vadher 2018-08-16 12:27:20

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

if($(selector).val())

@Jonas Lundman 2018-03-17 02:54:24

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.

@sina_Islam 2017-10-16 14:23:49

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");
                }

            });
        });

@Roland 2017-11-14 08:46:06

This way you put it into global namespace. Which you may want to reconsider.

@Tilak Maddy 2017-03-22 14:32:49

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();

@Andrei Todorut 2017-06-20 09:43:38

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

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}

@Jake McGraw 2008-08-27 19:50:03

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

@vsync 2009-11-24 09:22:59

I just write: if( $(selector).length ){ ... } without the '> 0'

@C Snover 2010-05-30 04:14:28

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.

@Ben Zotto 2010-08-02 20:52:03

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

@redsquare 2010-08-03 00:13:13

@quixoto, sorry but .length is a standard across many languages that does not need wrapping. How else do you interpret .length?

@Ben Zotto 2010-08-03 00:29:08

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.

@KitsuneYMG 2014-03-05 19:27:54

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

@cowbert 2015-06-01 09:06:37

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

@earnaz 2015-09-16 16:19:43

Great answer...but try any number, for example: $(666).exists() //the result is true (wrong)

@AndFisher 2017-08-24 11:39:36

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.

@Will Hoskings 2019-01-20 16:15:56

@CSnover I love how you go on about performance on a jQuery question.

@Oliver 2019-02-13 10:49:56

@earnaz That's also what I have found. And I didn't like it. That's why I've proposed an implementation that truly detects only DOM elements in the current document: stackoverflow.com/a/33111577/177710

@Pawel 2016-11-28 10:43:34

No need for jQuery

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

@Tim Büthe 2009-02-25 19:16:21

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

if ($(selector).length)

You don't need that >0 part.

@abhirathore2006 2016-07-31 06:46:16

this will throw error if you use Id selector if element doesn't exist. checkout the various tests i have done ...in my answer

@Robert 2017-06-29 20:35:22

@abhirathore2006 If you use an id selector and the element doesn't exist then length is 0 and doesn't throw exceptions.

@Robert 2017-06-29 20:52:47

Interestingly enough NaN != false.

@James 2017-07-04 15:55:09

@Robert and [] + [] = ""... ahh I love javascript

@Ismael Miguel 2017-07-08 22:09:38

@James That's because [].toString() === [].join(',') === "" and "" === "".

@debute 2017-08-09 13:54:21

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

@Alisson 2017-08-15 11:39:03

Will this call iterate over all DOM elements, or as soon as the first element matches the predicate it will be true and stop iterating other elements? In C# there is a big difference between using items.Count > 0 and items.Any(), even though you're using $(selector).length instead of $(selector).length > 0.

@Tim Büthe 2017-08-15 16:07:59

@Alisson the selector will be evaluated $(selector) and afterwards length is just a property of type number. Accessing length is simply reading that property no DOM iteration involved.

@Sebastianb 2017-08-25 14:46:50

@debute the last one probably compares true (the boolean result of the first == ) with "", which is false. I.e.: [].toString() == [].join(',') == "" -> true == "" -> false

@lucrativelucas 2017-10-19 18:06:27

@Robert NaN != false, and NaN != NaN

@Назар Топольський 2017-12-01 12:55:02

@Robert NaN isn't equal to anything, including self, and this is by design. My guess is that in case of NaN != false false is being cast to 0

@Robert 2017-12-03 19:57:55

@Назар Топольський That's correct. And it wouldn't matter what false is being cast to. But I just think it's a bit weird that a comparison with NaN evaluates to true.

@oriadam 2018-01-31 11:06:28

@Robert and typeof NaN == 'number'

@Sinjai 2018-02-14 05:09:03

Is there a tangible benefit to not including the > 0 part? Seems clearer to me that way.

@Will Hoskings 2018-03-10 16:07:18

what about if (($(selector)||{}).length)? that would supress errors,right?

@Marie 2018-03-13 16:58:12

@WillHoskings jQuery returns an augmented array with results. it will never error. Beyond that objects dont generally have a length property so that is a bit nonsensical.

@Will Hoskings 2018-03-13 20:38:04

When I use an invalid selector, it returns null. Not too sure if I'm up to date though.

@Vivek 2019-01-14 12:57:40

null is falsy as well

@abhirathore2006 2016-07-31 06:42:16

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

@Béranger 2016-09-09 12:27:18

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

@Jonathan Cardoz 2016-08-23 13:37:49

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
}

@Sunil Kumar 2016-07-26 05:32:26

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

@Star 2017-08-10 13:20:14

if "ElementID" doesn't exist then it will not throw error in if condition?

@Yanni 2011-04-03 12:17:06

You can use this:

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

// if element does not exist
if(!$('selector').length){ /* do something */ }

@Th4t Guy 2014-07-31 17:28:18

Did you not see that Tim Büthe had already given this answer 2 years prior to you?

@Jeremy W 2015-08-05 15:03:19

Pfft, Tim never showed how to test if the element does not exist.

@RichieHH 2017-07-02 12:55:43

You mean life "else"? My Q is this : err, it must exist or the selector doesn't match. The length is superfluous.

@aswzen 2018-04-03 08:48:01

this answer and comments sums up how stackoverflow works

@Sanu Uthaiah Bollera 2016-06-18 22:37:03

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

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

@SpYk3HH 2012-11-09 17:47:58

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    */
    }
})

@Chris Marisic 2016-06-16 17:46:29

On the callback version, shouldn't the Has Items callback actually pass in the object as an argument?

@Anurag Deokar 2015-07-09 12:39:01

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
}

@Pranav Labhe 2015-08-22 11:22:53

You need not to check weather length is greater than 0, if( $('#elementid').length ) { } will be sufficient.

@A1rPun 2016-03-16 16:01:29

Have you actually read the question? It's exactly the same method OP is using.

@Amitābha 2013-06-01 07:20:02

You could use this:

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

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

@ducdhm 2016-03-08 17:06:55

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
    }
);

@Oliver 2015-10-13 20:01:38

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>

@guest271314 2015-08-09 02:55:59

Try testing for DOM element

if (!!$(selector)[0]) // do stuff

@Jon Erickson 2009-01-14 19:46:05

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 */ }

@strager 2009-01-14 20:00:14

The first method reads better. $("a").exists() reads as "if <a> elements exist." $.exists("a") reads as "if there exists <a> elements."

@Jon Erickson 2009-01-15 00:31:45

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 =*(

@Matthew Crumley 2009-01-16 05:42:56

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.

@Jon Erickson 2009-01-20 20:05:32

That is very true Matthew, thanks for pointing that out, i guess it is just a matter of preference.

@Josh Stodola 2009-11-06 16:50:39

Even your second example isn't chainable...

@Ben Blank 2010-09-08 06:43:48

Why on earth would you need to chain this? $(".missing").css("color", "red") already does the right thing… (i.e. nothing)

@nickb 2010-09-14 19:16:38

First example ($('.mySelector').length) works fine, no need to create an exists() wrapper for it.

@Christian 2010-09-17 07:18:59

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

@Alnitak 2014-07-18 08:12:46

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.

@Emile Bergeron 2016-10-08 00:48:27

$("<div></div>").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.

@Santiago Hernández 2015-05-04 03:31:21

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

@user7892745 2017-05-22 21:47:29

Because Boolean(x) can sometimes be more efficient.

@Eternal1 2014-07-28 10:50:46

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

@Lev 2014-08-05 07:31:29

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.

@Eternal1 2014-08-05 07:38:51

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.

@Jarvl 2016-06-24 18:55:05

In what complex situation would this approach be better than a simple if/else statement?

Related Questions

Sponsored Content

10 Answered Questions

37 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

9 Answered Questions

[SOLVED] Check if object is a jQuery object

  • 2009-12-05 19:43:16
  • David Hellsing
  • 150104 View
  • 564 Score
  • 9 Answer
  • Tags:   javascript jquery

27 Answered Questions

[SOLVED] jQuery scroll to element

  • 2011-07-13 09:49:44
  • DiegoP.
  • 2157207 View
  • 2030 Score
  • 27 Answer
  • Tags:   javascript jquery

40 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

15 Answered Questions

[SOLVED] "Thinking in AngularJS" if I have a jQuery background?

59 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

31 Answered Questions

[SOLVED] endsWith in JavaScript

Sponsored Content