Is there an “exists” function for jQuery?












2523















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?










share|improve this question

























  • I don't know, what is 'in-elegant' in the first place.

    – yunzen
    Nov 20 '18 at 13:06
















2523















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?










share|improve this question

























  • I don't know, what is 'in-elegant' in the first place.

    – yunzen
    Nov 20 '18 at 13:06














2523












2523








2523


403






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?










share|improve this question
















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?







javascript jquery






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 16 '17 at 11:29









René

3,51221635




3,51221635










asked Aug 27 '08 at 19:49









Jake McGrawJake McGraw

33.2k104162




33.2k104162













  • I don't know, what is 'in-elegant' in the first place.

    – yunzen
    Nov 20 '18 at 13:06



















  • I don't know, what is 'in-elegant' in the first place.

    – yunzen
    Nov 20 '18 at 13:06

















I don't know, what is 'in-elegant' in the first place.

– yunzen
Nov 20 '18 at 13:06





I don't know, what is 'in-elegant' in the first place.

– yunzen
Nov 20 '18 at 13:06












40 Answers
40






active

oldest

votes













1 2
next












2253














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.






share|improve this answer





















  • 6





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

    – abhirathore2006
    Jul 31 '16 at 6:46






  • 41





    @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






  • 12





    Interestingly enough NaN != false.

    – Robert
    Jun 29 '17 at 20:52






  • 22





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

    – James
    Jul 4 '17 at 15:55






  • 3





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

    – Ismael Miguel
    Jul 8 '17 at 22:09





















1304














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






share|improve this answer





















  • 248





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

    – vsync
    Nov 24 '09 at 9:22






  • 355





    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 4:14








  • 204





    @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






  • 45





    @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






  • 132





    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





















354














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





















  • 10





    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






  • 15





    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






  • 16





    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






  • 36





    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








  • 8





    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 8:12



















125














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





















  • 123





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

    – Th4t Guy
    Jul 31 '14 at 17:28






  • 88





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

    – Jeremy W
    Aug 5 '15 at 15:03











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

    – RichieHH
    Jul 2 '17 at 12:55






  • 14





    this answer and comments sums up how stackoverflow works

    – aswzen
    Apr 3 '18 at 8:48



















88














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





















  • 51





    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






  • 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 8:55






  • 28





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

    – Blue Skies
    Dec 8 '13 at 0:43








  • 33





    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






  • 22





    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





















64














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



















  • 1





    I came here to post this exact answer... obligatory fiddle: 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



















57














You can use:



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


A little more elegant, perhaps.






share|improve this answer



















  • 36





    This is too much for such a simple thing. see Tim Büthe answer

    – vsync
    Nov 24 '09 at 9: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











  • 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 8 '16 at 12:55











  • @earnaz to avoid that specific case, $.find(666).length works.

    – Emile Bergeron
    Oct 8 '16 at 0:41



















57














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





share|improve this answer





















  • 1





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

    – Chris Marisic
    Jun 16 '16 at 17:46



















53














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





share|improve this answer

































    51














    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





















    • 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



















    47














    You could use this:



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

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





    share|improve this answer

































      40














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





      share|improve this answer

































        35














        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





















        • 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 $()?

          – cpburnz
          Mar 26 '15 at 15:46






        • 6





          @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





















        34














        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





















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

          – user1106925
          Jun 4 '16 at 13:28



















        33














        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
        }





        share|improve this answer





















        • 4





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

          – Pranav Labhe
          Aug 22 '15 at 11:22






        • 13





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

          – A1rPun
          Mar 16 '16 at 16:01



















        30














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






        share|improve this answer

































          27














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





          share|improve this answer



















          • 2





            Because Boolean(x) can sometimes be more efficient.

            – user7892745
            May 22 '17 at 21:47





















          26














          $(selector).length && //Do something





          share|improve this answer



















          • 17





            I hate these clever ways of avoiding to use an if where an if would improve readability at the cost of 2 bytes.

            – Emile Bergeron
            Oct 8 '16 at 0:35











          • Plus, minifiers will do all these && for you.

            – user7892745
            May 22 '17 at 21:46



















          25














          Try testing for DOM element



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





          share|improve this answer































            24














            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>








            share|improve this answer

































              23














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



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





              share|improve this answer































                22














                No need for jQuery



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





                share|improve this answer































                  20














                  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





                  share|improve this answer





















                  • 8





                    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 '14 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 '14 at 7:38






                  • 3





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

                    – Jarvl
                    Jun 24 '16 at 18:55



















                  18














                  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































                    17














                    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



















                    • 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



















                    14














                    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/






                    share|improve this answer































                      14














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





                      share|improve this answer





















                      • 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



















                      13














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





                      share|improve this answer































                        11














                        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
                        }





                        share|improve this answer































                          10














                          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





                          share|improve this answer


























                          • 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 9 '16 at 12:27















                          1 2
                          next


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



                          Thank you for your interest in this question.
                          Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



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














                          40 Answers
                          40






                          active

                          oldest

                          votes








                          40 Answers
                          40






                          active

                          oldest

                          votes









                          active

                          oldest

                          votes






                          active

                          oldest

                          votes








                          1 2
                          next










                          2253














                          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.






                          share|improve this answer





















                          • 6





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

                            – abhirathore2006
                            Jul 31 '16 at 6:46






                          • 41





                            @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






                          • 12





                            Interestingly enough NaN != false.

                            – Robert
                            Jun 29 '17 at 20:52






                          • 22





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

                            – James
                            Jul 4 '17 at 15:55






                          • 3





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

                            – Ismael Miguel
                            Jul 8 '17 at 22:09


















                          2253














                          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.






                          share|improve this answer





















                          • 6





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

                            – abhirathore2006
                            Jul 31 '16 at 6:46






                          • 41





                            @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






                          • 12





                            Interestingly enough NaN != false.

                            – Robert
                            Jun 29 '17 at 20:52






                          • 22





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

                            – James
                            Jul 4 '17 at 15:55






                          • 3





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

                            – Ismael Miguel
                            Jul 8 '17 at 22:09
















                          2253












                          2253








                          2253







                          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.






                          share|improve this answer















                          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.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Oct 17 '16 at 14:52

























                          answered Feb 25 '09 at 19:16









                          Tim BütheTim Büthe

                          48.2k1273120




                          48.2k1273120








                          • 6





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

                            – abhirathore2006
                            Jul 31 '16 at 6:46






                          • 41





                            @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






                          • 12





                            Interestingly enough NaN != false.

                            – Robert
                            Jun 29 '17 at 20:52






                          • 22





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

                            – James
                            Jul 4 '17 at 15:55






                          • 3





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

                            – Ismael Miguel
                            Jul 8 '17 at 22:09
















                          • 6





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

                            – abhirathore2006
                            Jul 31 '16 at 6:46






                          • 41





                            @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






                          • 12





                            Interestingly enough NaN != false.

                            – Robert
                            Jun 29 '17 at 20:52






                          • 22





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

                            – James
                            Jul 4 '17 at 15:55






                          • 3





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

                            – Ismael Miguel
                            Jul 8 '17 at 22:09










                          6




                          6





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

                          – abhirathore2006
                          Jul 31 '16 at 6:46





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

                          – abhirathore2006
                          Jul 31 '16 at 6:46




                          41




                          41





                          @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





                          @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




                          12




                          12





                          Interestingly enough NaN != false.

                          – Robert
                          Jun 29 '17 at 20:52





                          Interestingly enough NaN != false.

                          – Robert
                          Jun 29 '17 at 20:52




                          22




                          22





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

                          – James
                          Jul 4 '17 at 15:55





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

                          – James
                          Jul 4 '17 at 15:55




                          3




                          3





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

                          – Ismael Miguel
                          Jul 8 '17 at 22:09







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

                          – Ismael Miguel
                          Jul 8 '17 at 22:09















                          1304














                          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






                          share|improve this answer





















                          • 248





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

                            – vsync
                            Nov 24 '09 at 9:22






                          • 355





                            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 4:14








                          • 204





                            @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






                          • 45





                            @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






                          • 132





                            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


















                          1304














                          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






                          share|improve this answer





















                          • 248





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

                            – vsync
                            Nov 24 '09 at 9:22






                          • 355





                            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 4:14








                          • 204





                            @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






                          • 45





                            @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






                          • 132





                            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
















                          1304












                          1304








                          1304







                          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






                          share|improve this answer















                          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







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Feb 13 '17 at 22:37









                          vaxquis

                          7,74853958




                          7,74853958










                          answered Aug 27 '08 at 19:50









                          Jake McGrawJake McGraw

                          33.2k104162




                          33.2k104162








                          • 248





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

                            – vsync
                            Nov 24 '09 at 9:22






                          • 355





                            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 4:14








                          • 204





                            @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






                          • 45





                            @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






                          • 132





                            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
















                          • 248





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

                            – vsync
                            Nov 24 '09 at 9:22






                          • 355





                            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 4:14








                          • 204





                            @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






                          • 45





                            @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






                          • 132





                            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










                          248




                          248





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

                          – vsync
                          Nov 24 '09 at 9:22





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

                          – vsync
                          Nov 24 '09 at 9:22




                          355




                          355





                          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 4:14







                          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 4:14






                          204




                          204





                          @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





                          @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




                          45




                          45





                          @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





                          @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




                          132




                          132





                          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







                          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













                          354














                          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





















                          • 10





                            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






                          • 15





                            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






                          • 16





                            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






                          • 36





                            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








                          • 8





                            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 8:12
















                          354














                          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





















                          • 10





                            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






                          • 15





                            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






                          • 16





                            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






                          • 36





                            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








                          • 8





                            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 8:12














                          354












                          354








                          354







                          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















                          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














                          share|improve this answer



                          share|improve this answer








                          edited Jun 30 '15 at 8:09









                          R3tep

                          8,00982962




                          8,00982962










                          answered Jan 14 '09 at 19:46









                          Jon EricksonJon Erickson

                          77.2k34125160




                          77.2k34125160








                          • 10





                            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






                          • 15





                            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






                          • 16





                            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






                          • 36





                            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








                          • 8





                            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 8:12














                          • 10





                            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






                          • 15





                            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






                          • 16





                            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






                          • 36





                            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








                          • 8





                            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 8:12








                          10




                          10





                          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





                          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




                          15




                          15





                          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





                          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




                          16




                          16





                          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





                          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




                          36




                          36





                          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







                          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






                          8




                          8





                          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 8:12





                          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 8:12











                          125














                          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





















                          • 123





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

                            – Th4t Guy
                            Jul 31 '14 at 17:28






                          • 88





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

                            – Jeremy W
                            Aug 5 '15 at 15:03











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

                            – RichieHH
                            Jul 2 '17 at 12:55






                          • 14





                            this answer and comments sums up how stackoverflow works

                            – aswzen
                            Apr 3 '18 at 8:48
















                          125














                          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





















                          • 123





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

                            – Th4t Guy
                            Jul 31 '14 at 17:28






                          • 88





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

                            – Jeremy W
                            Aug 5 '15 at 15:03











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

                            – RichieHH
                            Jul 2 '17 at 12:55






                          • 14





                            this answer and comments sums up how stackoverflow works

                            – aswzen
                            Apr 3 '18 at 8:48














                          125












                          125








                          125







                          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















                          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














                          share|improve this answer



                          share|improve this answer








                          edited Jun 29 '16 at 4:43









                          Derek 朕會功夫

                          62.4k37141192




                          62.4k37141192










                          answered Apr 3 '11 at 12:17









                          YanniYanni

                          2,2072156




                          2,2072156








                          • 123





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

                            – Th4t Guy
                            Jul 31 '14 at 17:28






                          • 88





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

                            – Jeremy W
                            Aug 5 '15 at 15:03











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

                            – RichieHH
                            Jul 2 '17 at 12:55






                          • 14





                            this answer and comments sums up how stackoverflow works

                            – aswzen
                            Apr 3 '18 at 8:48














                          • 123





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

                            – Th4t Guy
                            Jul 31 '14 at 17:28






                          • 88





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

                            – Jeremy W
                            Aug 5 '15 at 15:03











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

                            – RichieHH
                            Jul 2 '17 at 12:55






                          • 14





                            this answer and comments sums up how stackoverflow works

                            – aswzen
                            Apr 3 '18 at 8:48








                          123




                          123





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

                          – Th4t Guy
                          Jul 31 '14 at 17:28





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

                          – Th4t Guy
                          Jul 31 '14 at 17:28




                          88




                          88





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

                          – Jeremy W
                          Aug 5 '15 at 15:03





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

                          – Jeremy W
                          Aug 5 '15 at 15:03













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

                          – RichieHH
                          Jul 2 '17 at 12:55





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

                          – RichieHH
                          Jul 2 '17 at 12:55




                          14




                          14





                          this answer and comments sums up how stackoverflow works

                          – aswzen
                          Apr 3 '18 at 8:48





                          this answer and comments sums up how stackoverflow works

                          – aswzen
                          Apr 3 '18 at 8:48











                          88














                          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





















                          • 51





                            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






                          • 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 8:55






                          • 28





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

                            – Blue Skies
                            Dec 8 '13 at 0:43








                          • 33





                            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






                          • 22





                            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


















                          88














                          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





















                          • 51





                            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






                          • 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 8:55






                          • 28





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

                            – Blue Skies
                            Dec 8 '13 at 0:43








                          • 33





                            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






                          • 22





                            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
















                          88












                          88








                          88







                          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















                          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














                          share|improve this answer



                          share|improve this answer








                          edited Feb 9 at 3:48









                          Randika Vishman

                          4,80724060




                          4,80724060










                          answered Jan 11 '12 at 12:27









                          MagneMagne

                          10.9k64759




                          10.9k64759








                          • 51





                            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






                          • 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 8:55






                          • 28





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

                            – Blue Skies
                            Dec 8 '13 at 0:43








                          • 33





                            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






                          • 22





                            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
















                          • 51





                            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






                          • 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 8:55






                          • 28





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

                            – Blue Skies
                            Dec 8 '13 at 0:43








                          • 33





                            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






                          • 22





                            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










                          51




                          51





                          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





                          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




                          7




                          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 8:55





                          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




                          28




                          28





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

                          – Blue Skies
                          Dec 8 '13 at 0:43







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

                          – Blue Skies
                          Dec 8 '13 at 0:43






                          33




                          33





                          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





                          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




                          22




                          22





                          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







                          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













                          64














                          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



















                          • 1





                            I came here to post this exact answer... obligatory fiddle: 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
















                          64














                          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



















                          • 1





                            I came here to post this exact answer... obligatory fiddle: 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














                          64












                          64








                          64







                          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













                          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












                          share|improve this answer



                          share|improve this answer










                          answered Jan 18 '14 at 9:04









                          Salman ASalman A

                          184k67343441




                          184k67343441








                          • 1





                            I came here to post this exact answer... obligatory fiddle: 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














                          • 1





                            I came here to post this exact answer... obligatory fiddle: 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








                          1




                          1





                          I came here to post this exact answer... obligatory fiddle: jsfiddle.net/jasonwilczak/ekjj80gy/2

                          – JasonWilczak
                          Mar 25 '15 at 15:08





                          I came here to post this exact answer... obligatory fiddle: jsfiddle.net/jasonwilczak/ekjj80gy/2

                          – JasonWilczak
                          Mar 25 '15 at 15:08




                          3




                          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







                          @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




                          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







                          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




                          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





                          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











                          57














                          You can use:



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


                          A little more elegant, perhaps.






                          share|improve this answer



















                          • 36





                            This is too much for such a simple thing. see Tim Büthe answer

                            – vsync
                            Nov 24 '09 at 9: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











                          • 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 8 '16 at 12:55











                          • @earnaz to avoid that specific case, $.find(666).length works.

                            – Emile Bergeron
                            Oct 8 '16 at 0:41
















                          57














                          You can use:



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


                          A little more elegant, perhaps.






                          share|improve this answer



















                          • 36





                            This is too much for such a simple thing. see Tim Büthe answer

                            – vsync
                            Nov 24 '09 at 9: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











                          • 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 8 '16 at 12:55











                          • @earnaz to avoid that specific case, $.find(666).length works.

                            – Emile Bergeron
                            Oct 8 '16 at 0:41














                          57












                          57








                          57







                          You can use:



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


                          A little more elegant, perhaps.






                          share|improve this answer













                          You can use:



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


                          A little more elegant, perhaps.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 17 '08 at 17:53









                          DevonDevon

                          4,46943444




                          4,46943444








                          • 36





                            This is too much for such a simple thing. see Tim Büthe answer

                            – vsync
                            Nov 24 '09 at 9: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











                          • 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 8 '16 at 12:55











                          • @earnaz to avoid that specific case, $.find(666).length works.

                            – Emile Bergeron
                            Oct 8 '16 at 0:41














                          • 36





                            This is too much for such a simple thing. see Tim Büthe answer

                            – vsync
                            Nov 24 '09 at 9: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











                          • 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 8 '16 at 12:55











                          • @earnaz to avoid that specific case, $.find(666).length works.

                            – Emile Bergeron
                            Oct 8 '16 at 0:41








                          36




                          36





                          This is too much for such a simple thing. see Tim Büthe answer

                          – vsync
                          Nov 24 '09 at 9:28





                          This is too much for such a simple thing. see Tim Büthe answer

                          – vsync
                          Nov 24 '09 at 9: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





                          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













                          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







                          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




                          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 8 '16 at 12:55





                          @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 8 '16 at 12:55













                          @earnaz to avoid that specific case, $.find(666).length works.

                          – Emile Bergeron
                          Oct 8 '16 at 0:41





                          @earnaz to avoid that specific case, $.find(666).length works.

                          – Emile Bergeron
                          Oct 8 '16 at 0:41











                          57














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





                          share|improve this answer





















                          • 1





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

                            – Chris Marisic
                            Jun 16 '16 at 17:46
















                          57














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





                          share|improve this answer





















                          • 1





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

                            – Chris Marisic
                            Jun 16 '16 at 17:46














                          57












                          57








                          57







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





                          share|improve this answer















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






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Jun 12 '16 at 9:10


























                          community wiki





                          22 revs, 6 users 64%
                          SpYk3HH









                          • 1





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

                            – Chris Marisic
                            Jun 16 '16 at 17:46














                          • 1





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

                            – Chris Marisic
                            Jun 16 '16 at 17:46








                          1




                          1





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

                          – Chris Marisic
                          Jun 16 '16 at 17:46





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

                          – Chris Marisic
                          Jun 16 '16 at 17:46











                          53














                          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





                          share|improve this answer






























                            53














                            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





                            share|improve this answer




























                              53












                              53








                              53







                              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





                              share|improve this answer















                              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






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jan 18 at 23:49

























                              answered May 20 '17 at 9:21









                              AlirezaAlireza

                              51.5k13175124




                              51.5k13175124























                                  51














                                  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





















                                  • 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
















                                  51














                                  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





















                                  • 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














                                  51












                                  51








                                  51







                                  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















                                  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














                                  share|improve this answer



                                  share|improve this answer








                                  edited May 10 '13 at 7:48









                                  Peter Mortensen

                                  13.8k1987113




                                  13.8k1987113










                                  answered Nov 14 '11 at 14:20









                                  amypellegriniamypellegrini

                                  929813




                                  929813








                                  • 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














                                  • 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








                                  5




                                  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





                                  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











                                  47














                                  You could use this:



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

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





                                  share|improve this answer






























                                    47














                                    You could use this:



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

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





                                    share|improve this answer




























                                      47












                                      47








                                      47







                                      You could use this:



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

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





                                      share|improve this answer















                                      You could use this:



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

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






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Mar 15 '16 at 7:46









                                      Bellash

                                      3,99512659




                                      3,99512659










                                      answered Jun 1 '13 at 7:20









                                      AmitābhaAmitābha

                                      1,70542242




                                      1,70542242























                                          40














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





                                          share|improve this answer






























                                            40














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





                                            share|improve this answer




























                                              40












                                              40








                                              40







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





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






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Aug 13 '14 at 5:24

























                                              answered Aug 11 '14 at 23:42









                                              technosaurustechnosaurus

                                              6,04012245




                                              6,04012245























                                                  35














                                                  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





















                                                  • 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 $()?

                                                    – cpburnz
                                                    Mar 26 '15 at 15:46






                                                  • 6





                                                    @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


















                                                  35














                                                  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





















                                                  • 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 $()?

                                                    – cpburnz
                                                    Mar 26 '15 at 15:46






                                                  • 6





                                                    @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
















                                                  35












                                                  35








                                                  35







                                                  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















                                                  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














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Feb 7 '12 at 17:43

























                                                  answered Feb 6 '12 at 20:37









                                                  OlegOleg

                                                  7,55423455




                                                  7,55423455








                                                  • 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 $()?

                                                    – cpburnz
                                                    Mar 26 '15 at 15:46






                                                  • 6





                                                    @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
















                                                  • 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 $()?

                                                    – cpburnz
                                                    Mar 26 '15 at 15:46






                                                  • 6





                                                    @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










                                                  12




                                                  12





                                                  How often do you find yourself calling $() with an empty object as an argument?

                                                  – nnnnnn
                                                  Dec 22 '14 at 11:24





                                                  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





                                                  @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




                                                  3





                                                  Why on earth would you pass an empty object {} to $()?

                                                  – cpburnz
                                                  Mar 26 '15 at 15:46





                                                  Why on earth would you pass an empty object {} to $()?

                                                  – cpburnz
                                                  Mar 26 '15 at 15:46




                                                  6




                                                  6





                                                  @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





                                                  @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




                                                  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







                                                  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













                                                  34














                                                  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





















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

                                                    – user1106925
                                                    Jun 4 '16 at 13:28
















                                                  34














                                                  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





















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

                                                    – user1106925
                                                    Jun 4 '16 at 13:28














                                                  34












                                                  34








                                                  34







                                                  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















                                                  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














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Oct 28 '18 at 9:57









                                                  Mohammad

                                                  15.8k123765




                                                  15.8k123765










                                                  answered Oct 23 '13 at 5:46









                                                  hiwayhiway

                                                  2,03782548




                                                  2,03782548








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

                                                    – user1106925
                                                    Jun 4 '16 at 13:28














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

                                                    – user1106925
                                                    Jun 4 '16 at 13:28








                                                  3




                                                  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.

                                                  – user1106925
                                                  Jun 4 '16 at 13:28





                                                  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.

                                                  – user1106925
                                                  Jun 4 '16 at 13:28











                                                  33














                                                  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
                                                  }





                                                  share|improve this answer





















                                                  • 4





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

                                                    – Pranav Labhe
                                                    Aug 22 '15 at 11:22






                                                  • 13





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

                                                    – A1rPun
                                                    Mar 16 '16 at 16:01
















                                                  33














                                                  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
                                                  }





                                                  share|improve this answer





















                                                  • 4





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

                                                    – Pranav Labhe
                                                    Aug 22 '15 at 11:22






                                                  • 13





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

                                                    – A1rPun
                                                    Mar 16 '16 at 16:01














                                                  33












                                                  33








                                                  33







                                                  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
                                                  }





                                                  share|improve this answer















                                                  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
                                                  }






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Apr 11 '16 at 13:21

























                                                  answered Jul 9 '15 at 12:39









                                                  Anurag DeokarAnurag Deokar

                                                  686612




                                                  686612








                                                  • 4





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

                                                    – Pranav Labhe
                                                    Aug 22 '15 at 11:22






                                                  • 13





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

                                                    – A1rPun
                                                    Mar 16 '16 at 16:01














                                                  • 4





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

                                                    – Pranav Labhe
                                                    Aug 22 '15 at 11:22






                                                  • 13





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

                                                    – A1rPun
                                                    Mar 16 '16 at 16:01








                                                  4




                                                  4





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

                                                  – Pranav Labhe
                                                  Aug 22 '15 at 11:22





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

                                                  – Pranav Labhe
                                                  Aug 22 '15 at 11:22




                                                  13




                                                  13





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

                                                  – A1rPun
                                                  Mar 16 '16 at 16:01





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

                                                  – A1rPun
                                                  Mar 16 '16 at 16:01











                                                  30














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






                                                  share|improve this answer






























                                                    30














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






                                                    share|improve this answer




























                                                      30












                                                      30








                                                      30







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






                                                      share|improve this answer















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







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Sep 10 '17 at 10:31









                                                      Palec

                                                      7,61454290




                                                      7,61454290










                                                      answered Mar 22 '17 at 14:32









                                                      Tilak MaddyTilak Maddy

                                                      1,52311333




                                                      1,52311333























                                                          27














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





                                                          share|improve this answer



















                                                          • 2





                                                            Because Boolean(x) can sometimes be more efficient.

                                                            – user7892745
                                                            May 22 '17 at 21:47


















                                                          27














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





                                                          share|improve this answer



















                                                          • 2





                                                            Because Boolean(x) can sometimes be more efficient.

                                                            – user7892745
                                                            May 22 '17 at 21:47
















                                                          27












                                                          27








                                                          27







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





                                                          share|improve this answer













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






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered May 4 '15 at 3:31









                                                          Santiago HernándezSantiago Hernández

                                                          3,10611732




                                                          3,10611732








                                                          • 2





                                                            Because Boolean(x) can sometimes be more efficient.

                                                            – user7892745
                                                            May 22 '17 at 21:47
















                                                          • 2





                                                            Because Boolean(x) can sometimes be more efficient.

                                                            – user7892745
                                                            May 22 '17 at 21:47










                                                          2




                                                          2





                                                          Because Boolean(x) can sometimes be more efficient.

                                                          – user7892745
                                                          May 22 '17 at 21:47







                                                          Because Boolean(x) can sometimes be more efficient.

                                                          – user7892745
                                                          May 22 '17 at 21:47













                                                          26














                                                          $(selector).length && //Do something





                                                          share|improve this answer



















                                                          • 17





                                                            I hate these clever ways of avoiding to use an if where an if would improve readability at the cost of 2 bytes.

                                                            – Emile Bergeron
                                                            Oct 8 '16 at 0:35











                                                          • Plus, minifiers will do all these && for you.

                                                            – user7892745
                                                            May 22 '17 at 21:46
















                                                          26














                                                          $(selector).length && //Do something





                                                          share|improve this answer



















                                                          • 17





                                                            I hate these clever ways of avoiding to use an if where an if would improve readability at the cost of 2 bytes.

                                                            – Emile Bergeron
                                                            Oct 8 '16 at 0:35











                                                          • Plus, minifiers will do all these && for you.

                                                            – user7892745
                                                            May 22 '17 at 21:46














                                                          26












                                                          26








                                                          26







                                                          $(selector).length && //Do something





                                                          share|improve this answer













                                                          $(selector).length && //Do something






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered May 28 '12 at 12:58









                                                          SJGSJG

                                                          1,62311410




                                                          1,62311410








                                                          • 17





                                                            I hate these clever ways of avoiding to use an if where an if would improve readability at the cost of 2 bytes.

                                                            – Emile Bergeron
                                                            Oct 8 '16 at 0:35











                                                          • Plus, minifiers will do all these && for you.

                                                            – user7892745
                                                            May 22 '17 at 21:46














                                                          • 17





                                                            I hate these clever ways of avoiding to use an if where an if would improve readability at the cost of 2 bytes.

                                                            – Emile Bergeron
                                                            Oct 8 '16 at 0:35











                                                          • Plus, minifiers will do all these && for you.

                                                            – user7892745
                                                            May 22 '17 at 21:46








                                                          17




                                                          17





                                                          I hate these clever ways of avoiding to use an if where an if would improve readability at the cost of 2 bytes.

                                                          – Emile Bergeron
                                                          Oct 8 '16 at 0:35





                                                          I hate these clever ways of avoiding to use an if where an if would improve readability at the cost of 2 bytes.

                                                          – Emile Bergeron
                                                          Oct 8 '16 at 0:35













                                                          Plus, minifiers will do all these && for you.

                                                          – user7892745
                                                          May 22 '17 at 21:46





                                                          Plus, minifiers will do all these && for you.

                                                          – user7892745
                                                          May 22 '17 at 21:46











                                                          25














                                                          Try testing for DOM element



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





                                                          share|improve this answer




























                                                            25














                                                            Try testing for DOM element



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





                                                            share|improve this answer


























                                                              25












                                                              25








                                                              25







                                                              Try testing for DOM element



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





                                                              share|improve this answer













                                                              Try testing for DOM element



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






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Aug 9 '15 at 2:55









                                                              guest271314guest271314

                                                              1




                                                              1























                                                                  24














                                                                  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>








                                                                  share|improve this answer






























                                                                    24














                                                                    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>








                                                                    share|improve this answer




























                                                                      24












                                                                      24








                                                                      24







                                                                      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>








                                                                      share|improve this answer















                                                                      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>








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





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






                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited May 23 '17 at 11:47









                                                                      Community

                                                                      11




                                                                      11










                                                                      answered Oct 13 '15 at 20:01









                                                                      OliverOliver

                                                                      6,82845179




                                                                      6,82845179























                                                                          23














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



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





                                                                          share|improve this answer




























                                                                            23














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



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





                                                                            share|improve this answer


























                                                                              23












                                                                              23








                                                                              23







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



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





                                                                              share|improve this answer













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



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






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Jun 18 '16 at 22:37









                                                                              Sanu Uthaiah BolleraSanu Uthaiah Bollera

                                                                              686810




                                                                              686810























                                                                                  22














                                                                                  No need for jQuery



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





                                                                                  share|improve this answer




























                                                                                    22














                                                                                    No need for jQuery



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





                                                                                    share|improve this answer


























                                                                                      22












                                                                                      22








                                                                                      22







                                                                                      No need for jQuery



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





                                                                                      share|improve this answer













                                                                                      No need for jQuery



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






                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered Nov 28 '16 at 10:43









                                                                                      PawelPawel

                                                                                      5,95433846




                                                                                      5,95433846























                                                                                          20














                                                                                          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





                                                                                          share|improve this answer





















                                                                                          • 8





                                                                                            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 '14 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 '14 at 7:38






                                                                                          • 3





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

                                                                                            – Jarvl
                                                                                            Jun 24 '16 at 18:55
















                                                                                          20














                                                                                          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





                                                                                          share|improve this answer





















                                                                                          • 8





                                                                                            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 '14 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 '14 at 7:38






                                                                                          • 3





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

                                                                                            – Jarvl
                                                                                            Jun 24 '16 at 18:55














                                                                                          20












                                                                                          20








                                                                                          20







                                                                                          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





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






                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited Apr 16 '15 at 9:17

























                                                                                          answered Jul 28 '14 at 10:50









                                                                                          Eternal1Eternal1

                                                                                          4,05612340




                                                                                          4,05612340








                                                                                          • 8





                                                                                            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 '14 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 '14 at 7:38






                                                                                          • 3





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

                                                                                            – Jarvl
                                                                                            Jun 24 '16 at 18:55














                                                                                          • 8





                                                                                            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 '14 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 '14 at 7:38






                                                                                          • 3





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

                                                                                            – Jarvl
                                                                                            Jun 24 '16 at 18:55








                                                                                          8




                                                                                          8





                                                                                          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 '14 at 7:31





                                                                                          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 '14 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 '14 at 7:38





                                                                                          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 '14 at 7:38




                                                                                          3




                                                                                          3





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

                                                                                          – Jarvl
                                                                                          Jun 24 '16 at 18:55





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

                                                                                          – Jarvl
                                                                                          Jun 24 '16 at 18:55











                                                                                          18














                                                                                          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




























                                                                                            18














                                                                                            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


























                                                                                              18












                                                                                              18








                                                                                              18







                                                                                              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













                                                                                              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












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered Apr 5 '12 at 21:02









                                                                                              jcreamer898jcreamer898

                                                                                              6,46843454




                                                                                              6,46843454























                                                                                                  17














                                                                                                  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



















                                                                                                  • 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
















                                                                                                  17














                                                                                                  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



















                                                                                                  • 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














                                                                                                  17












                                                                                                  17








                                                                                                  17







                                                                                                  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













                                                                                                  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












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Mar 4 '14 at 21:15









                                                                                                  GSTARGSTAR

                                                                                                  1,6431154101




                                                                                                  1,6431154101








                                                                                                  • 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














                                                                                                  • 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








                                                                                                  3




                                                                                                  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





                                                                                                  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











                                                                                                  14














                                                                                                  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/






                                                                                                  share|improve this answer




























                                                                                                    14














                                                                                                    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/






                                                                                                    share|improve this answer


























                                                                                                      14












                                                                                                      14








                                                                                                      14







                                                                                                      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/






                                                                                                      share|improve this answer













                                                                                                      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/







                                                                                                      share|improve this answer












                                                                                                      share|improve this answer



                                                                                                      share|improve this answer










                                                                                                      answered Aug 1 '12 at 21:56









                                                                                                      andy_314andy_314

                                                                                                      329314




                                                                                                      329314























                                                                                                          14














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





                                                                                                          share|improve this answer





















                                                                                                          • 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
















                                                                                                          14














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





                                                                                                          share|improve this answer





















                                                                                                          • 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














                                                                                                          14












                                                                                                          14








                                                                                                          14







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





                                                                                                          share|improve this answer















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






                                                                                                          share|improve this answer














                                                                                                          share|improve this answer



                                                                                                          share|improve this answer








                                                                                                          edited Jan 3 at 10:00









                                                                                                          Hydrothermal

                                                                                                          2,25371737




                                                                                                          2,25371737










                                                                                                          answered Mar 25 '16 at 11:05









                                                                                                          Kamuran SönecekKamuran Sönecek

                                                                                                          1,93021643




                                                                                                          1,93021643








                                                                                                          • 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














                                                                                                          • 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








                                                                                                          5




                                                                                                          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





                                                                                                          "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











                                                                                                          13














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





                                                                                                          share|improve this answer




























                                                                                                            13














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





                                                                                                            share|improve this answer


























                                                                                                              13












                                                                                                              13








                                                                                                              13







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





                                                                                                              share|improve this answer













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






                                                                                                              share|improve this answer












                                                                                                              share|improve this answer



                                                                                                              share|improve this answer










                                                                                                              answered Mar 8 '16 at 17:06









                                                                                                              ducdhmducdhm

                                                                                                              1,7061020




                                                                                                              1,7061020























                                                                                                                  11














                                                                                                                  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
                                                                                                                  }





                                                                                                                  share|improve this answer




























                                                                                                                    11














                                                                                                                    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
                                                                                                                    }





                                                                                                                    share|improve this answer


























                                                                                                                      11












                                                                                                                      11








                                                                                                                      11







                                                                                                                      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
                                                                                                                      }





                                                                                                                      share|improve this answer













                                                                                                                      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
                                                                                                                      }






                                                                                                                      share|improve this answer












                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer










                                                                                                                      answered Jun 20 '17 at 9:43









                                                                                                                      Andrei TodorutAndrei Todorut

                                                                                                                      2,1791615




                                                                                                                      2,1791615























                                                                                                                          10














                                                                                                                          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





                                                                                                                          share|improve this answer


























                                                                                                                          • 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 9 '16 at 12:27
















                                                                                                                          10














                                                                                                                          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





                                                                                                                          share|improve this answer


























                                                                                                                          • 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 9 '16 at 12:27














                                                                                                                          10












                                                                                                                          10








                                                                                                                          10







                                                                                                                          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





                                                                                                                          share|improve this answer















                                                                                                                          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






                                                                                                                          share|improve this answer














                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer








                                                                                                                          edited Oct 15 '16 at 7:10

























                                                                                                                          answered Jul 31 '16 at 6:42









                                                                                                                          abhirathore2006abhirathore2006

                                                                                                                          2,2421626




                                                                                                                          2,2421626













                                                                                                                          • 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 9 '16 at 12:27



















                                                                                                                          • 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 9 '16 at 12:27

















                                                                                                                          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 9 '16 at 12:27





                                                                                                                          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 9 '16 at 12:27










                                                                                                                          1 2
                                                                                                                          next




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



                                                                                                                          Thank you for your interest in this question.
                                                                                                                          Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



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



                                                                                                                          Popular posts from this blog

                                                                                                                          Mossoró

                                                                                                                          Error while reading .h5 file using the rhdf5 package in R

                                                                                                                          Pushsharp Apns notification error: 'InvalidToken'