<p>How can I check the existence of an element in jQuery?</p>

<p>The current code that I have is this:</p>

<pre><code>if ($(selector).length &gt; 0) {
    // Do something
}
</code></pre>

<p>Is there a more elegant way to approach this? Perhaps a plugin or a function?</p>

[{'answer_id': 31047, 'author': 'Jake McGraw', 'author_id': 302, 'author_profile': 'https://Stackoverflow.com/users/302', 'pm_score': 10, 'selected': False, 'text': '<p>Yes!</p>\n\n<pre><code>jQuery.fn.exists = function(){ return this.length &gt; 0; }\n\nif ($(selector).exists()) {\n    // Do something\n}\n</code></pre>\n\n<p>This is in response to: <a href="http://herdingcode.com/?p=36" rel="noreferrer">Herding Code podcast with Jeff Atwood</a></p>\n'}, {'answer_id': 85834, 'author': 'Devon', 'author_id': 13850, 'author_profile': 'https://Stackoverflow.com/users/13850', 'pm_score': 6, 'selected': False, 'text': "<p>You can use:</p>\n\n<pre><code>if ($(selector).is('*')) {\n  // Do something\n}\n</code></pre>\n\n<p>A <strong>little</strong> more elegant, perhaps.</p>\n"}, {'answer_id': 444403, 'author': 'Jon Erickson', 'author_id': 1950, 'author_profile': 'https://Stackoverflow.com/users/1950', 'pm_score': 9, 'selected': False, 'text': '<p>If you used</p>\n\n<pre><code>jQuery.fn.exists = function(){return ($(this).length &gt; 0);}\nif ($(selector).exists()) { }\n</code></pre>\n\n<p>you would imply that chaining was possible when it is not.</p>\n\n<p>This would be better:</p>\n\n<pre><code>jQuery.exists = function(selector) {return ($(selector).length &gt; 0);}\nif ($.exists(selector)) { }\n</code></pre>\n\n<p>Alternatively, <a href="http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/" rel="noreferrer">from the FAQ</a>:</p>\n\n<pre><code>if ( $(\'#myDiv\').length ) { /* Do something */ }\n</code></pre>\n\n<p>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.</p>\n\n<pre><code>if ( $(\'#myDiv\')[0] ) { /* Do something */ }\n</code></pre>\n'}, {'answer_id': 584536, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<pre><code>if ( $('#myDiv').size() &gt; 0 ) { //do something }\n</code></pre>\n\n<p><code>size()</code> counts the number of elements returned by the selector</p>\n"}, {'answer_id': 587408, 'author': 'Tim Büthe', 'author_id': 60518, 'author_profile': 'https://Stackoverflow.com/users/60518', 'pm_score': 12, 'selected': True, 'text': "<p>In JavaScript, everything is 'truthy' or 'falsy', and for numbers <code>0</code> means <code>false</code>, everything else <code>true</code>. So you could write:</p>\n<pre><code>if ($(selector).length)\n</code></pre>\n<p>You don't need that <code>&gt;0</code> part.</p>\n"}, {'answer_id': 5529517, 'author': 'Yanni', 'author_id': 689782, 'author_profile': 'https://Stackoverflow.com/users/689782', 'pm_score': 7, 'selected': False, 'text': "<p>You can use this:</p>\n\n<pre><code>// if element exists\nif($('selector').length){ /* do something */ }\n</code></pre>\n\n<hr>\n\n<pre><code>// if element does not exist\nif(!$('selector').length){ /* do something */ }\n</code></pre>\n"}, {'answer_id': 8122936, 'author': 'amypellegrini', 'author_id': 527050, 'author_profile': 'https://Stackoverflow.com/users/527050', 'pm_score': 6, 'selected': False, 'text': '<p>There\'s no need for jQuery really. With plain JavaScript it\'s easier and semantically correct to check for:</p>\n\n<pre><code>if(document.getElementById("myElement")) {\n    //Do something...\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>jQuery is really cool, but don\'t let pure JavaScript fall into oblivion...</p>\n'}, {'answer_id': 8819227, 'author': 'Magne', 'author_id': 380607, 'author_profile': 'https://Stackoverflow.com/users/380607', 'pm_score': 7, 'selected': False, 'text': "<p>The fastest and most semantically self explaining way to check for existence is actually by using plain <code>JavaScript</code>:</p>\n\n<pre><code>if (document.getElementById('element_id')) {\n    // Do something\n}\n</code></pre>\n\n<p>It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.</p>\n\n<p>And it is better than the alternative of writing your own <code>jQuery</code> function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the <code>exists()</code> function is something inherent to jQuery. <code>JavaScript</code> would/should be understood by others editing your code, without increased knowledge debt.</p>\n\n<p><strong>NB:</strong> Notice the lack of an '#' before the <code>element_id</code> (since this is plain JS, not <code>jQuery</code>).</p>\n"}, {'answer_id': 9166924, 'author': 'Oleg', 'author_id': 632133, 'author_profile': 'https://Stackoverflow.com/users/632133', 'pm_score': 5, 'selected': False, 'text': "<p>I have found <code>if ($(selector).length) {}</code> to be insufficient. It will silently break your app when <code>selector</code> is an empty object <code>{}</code>.</p>\n\n<pre><code>var $target = $({});        \nconsole.log($target, $target.length);\n\n// Console output:\n// -------------------------------------\n// [▼ Object              ] 1\n//    ► __proto__: Object\n</code></pre>\n\n<p>My only suggestion is to perform an additional check for <code>{}</code>.</p>\n\n<pre><code>if ($.isEmptyObject(selector) || !$(selector).length) {\n    throw new Error('Unable to work with the given selector.');\n}\n</code></pre>\n\n<p>I'm still looking for a better solution though as this one is a bit heavy.</p>\n\n<p>Edit: <strong>WARNING!</strong> This doesn't work in IE when <code>selector</code> is a string.</p>\n\n<pre><code>$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE\n</code></pre>\n"}, {'answer_id': 10035967, 'author': 'jcreamer898', 'author_id': 558672, 'author_profile': 'https://Stackoverflow.com/users/558672', 'pm_score': 4, 'selected': False, 'text': '<p>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..</p>\n\n<pre><code>// Checks if an object exists.\n// Usage:\n//\n//     $(selector).exists()\n//\n// Or:\n// \n//     $(selector).exists(anotherSelector);\njQuery.fn.exists = function(selector) {\n    return selector ? this.find(selector).length : this.length;\n};\n</code></pre>\n'}, {'answer_id': 10785067, 'author': 'SJG', 'author_id': 886435, 'author_profile': 'https://Stackoverflow.com/users/886435', 'pm_score': 5, 'selected': False, 'text': '<pre><code>$(selector).length &amp;&amp; //Do something\n</code></pre>\n'}, {'answer_id': 11768171, 'author': 'andy_314', 'author_id': 1101503, 'author_profile': 'https://Stackoverflow.com/users/1101503', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m using this:</p>\n\n<pre><code>    $.fn.ifExists = function(fn) {\n      if (this.length) {\n        $(fn(this));\n      }\n    };\n    $("#element").ifExists( \n      function($this){\n        $this.addClass(\'someClass\').animate({marginTop:20},function(){alert(\'ok\')});               \n      }\n    ); \n</code></pre>\n\n<p>Execute the chain only if a jQuery element exist  - <a href="http://jsfiddle.net/andres_314/vbNM3/2/">http://jsfiddle.net/andres_314/vbNM3/2/</a></p>\n'}, {'answer_id': 13313296, 'author': 'SpYk3HH', 'author_id': 900807, 'author_profile': 'https://Stackoverflow.com/users/900807', 'pm_score': 6, 'selected': False, 'text': '<p>This plugin can be used in an <code>if</code> statement like <code>if ($(ele).exist()) { /* DO WORK */ }</code> or using a callback.</p>\n\n<h2>Plugin</h2>\n\n<pre><code>;;(function($) {\n    if (!$.exist) {\n        $.extend({\n            exist: function() {\n                var ele, cbmExist, cbmNotExist;\n                if (arguments.length) {\n                    for (x in arguments) {\n                        switch (typeof arguments[x]) {\n                            case \'function\':\n                                if (typeof cbmExist == "undefined") cbmExist = arguments[x];\n                                else cbmNotExist = arguments[x];\n                                break;\n                            case \'object\':\n                                if (arguments[x] instanceof jQuery) ele = arguments[x];\n                                else {\n                                    var obj = arguments[x];\n                                    for (y in obj) {\n                                        if (typeof obj[y] == \'function\') {\n                                            if (typeof cbmExist == "undefined") cbmExist = obj[y];\n                                            else cbmNotExist = obj[y];\n                                        }\n                                        if (typeof obj[y] == \'object\' &amp;&amp; obj[y] instanceof jQuery) ele = obj[y];\n                                        if (typeof obj[y] == \'string\') ele = $(obj[y]);\n                                    }\n                                }\n                                break;\n                            case \'string\':\n                                ele = $(arguments[x]);\n                                break;\n                        }\n                    }\n                }\n\n                if (typeof cbmExist == \'function\') {\n                    var exist =  ele.length &gt; 0 ? true : false;\n                    if (exist) {\n                        return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });\n                    }\n                    else if (typeof cbmNotExist == \'function\') {\n                        cbmNotExist.apply(ele, [exist, ele]);\n                        return ele;\n                    }\n                    else {\n                        if (ele.length &lt;= 1) return ele.length &gt; 0 ? true : false;\n                        else return ele.length;\n                    }\n                }\n                else {\n                    if (ele.length &lt;= 1) return ele.length &gt; 0 ? true : false;\n                    else return ele.length;\n                }\n\n                return false;\n            }\n        });\n        $.fn.extend({\n            exist: function() {\n                var args = [$(this)];\n                if (arguments.length) for (x in arguments) args.push(arguments[x]);\n                return $.exist.apply($, args);\n            }\n        });\n    }\n})(jQuery);\n</code></pre>\n\n<p><a href="http://jsfiddle.net/SpYk3/cEUR5/">jsFiddle</a></p>\n\n<p>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 <em>not</em> 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 <em>not</em> exist. Of course, if it does exist, the first function will fire and the chain will continue.</p>\n\n<p>Keep in mind that using the <strong>callback variant helps maintain chainability</strong> – the element is returned and you can continue chaining commands as with any other jQuery method!</p>\n\n<h2>Example Uses</h2>\n\n<pre><code>if ($.exist(\'#eleID\')) {    /*    DO WORK    */ }        //    param as STRING\nif ($.exist($(\'#eleID\'))) { /*    DO WORK    */ }        //    param as jQuery OBJECT\nif ($(\'#eleID\').exist()) {  /*    DO WORK    */ }        //    enduced on jQuery OBJECT\n\n$.exist(\'#eleID\', function() {            //    param is STRING &amp;&amp; CALLBACK METHOD\n    /*    DO WORK    */\n    /*    This will ONLY fire if the element EXIST    */\n}, function() {            //    param is STRING &amp;&amp; CALLBACK METHOD\n    /*    DO WORK    */\n    /*    This will ONLY fire if the element DOES NOT EXIST    */\n})\n\n$(\'#eleID\').exist(function() {            //    enduced on jQuery OBJECT with CALLBACK METHOD\n    /*    DO WORK    */\n    /*    This will ONLY fire if the element EXIST    */\n})\n\n$.exist({                        //    param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD\n    element: \'#eleID\',\n    callback: function() {\n        /*    DO WORK    */\n        /*    This will ONLY fire if the element EXIST    */\n    }\n})\n</code></pre>\n'}, {'answer_id': 16870190, 'author': '王奕然', 'author_id': 2245634, 'author_profile': 'https://Stackoverflow.com/users/2245634', 'pm_score': 6, 'selected': False, 'text': '<p>You could use this:</p>\n\n<pre><code>jQuery.fn.extend({\n    exists: function() { return this.length }\n});\n\nif($(selector).exists()){/*do something*/}\n</code></pre>\n'}, {'answer_id': 19533724, 'author': 'hiway', 'author_id': 1626906, 'author_profile': 'https://Stackoverflow.com/users/1626906', 'pm_score': 6, 'selected': False, 'text': '<p>Is <a href="http://api.jquery.com/jQuery.contains/" rel="noreferrer"><code>$.contains()</code></a> what you want?</p>\n<blockquote>\n<p><code>jQuery.contains( container, contained )</code></p>\n<p>The <code>$.contains()</code> 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, <code>$.contains()</code> will return false.</p>\n<p><em><strong>Note</strong></em>: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.</p>\n</blockquote>\n'}, {'answer_id': 21202125, 'author': 'Salman A', 'author_id': 87015, 'author_profile': 'https://Stackoverflow.com/users/87015', 'pm_score': 6, 'selected': False, 'text': '<p>You can save a few bytes by writing:</p>\n\n<pre><code>if ($(selector)[0]) { ... }\n</code></pre>\n\n<p>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 <em>array</em>. It returns <code>undefined</code> if there is no item at the specified index.</p>\n'}, {'answer_id': 22183204, 'author': 'MAX POWER', 'author_id': 372630, 'author_profile': 'https://Stackoverflow.com/users/372630', 'pm_score': 4, 'selected': False, 'text': "<p>How about:</p>\n\n<pre><code>function exists(selector) {\n    return $(selector).length;\n}\n\nif (exists(selector)) {\n    // do something\n}\n</code></pre>\n\n<p>It's very minimal and saves you having to enclose the selector with <code>$()</code> every time.</p>\n"}, {'answer_id': 24993631, 'author': 'Eternal1', 'author_id': 2214752, 'author_profile': 'https://Stackoverflow.com/users/2214752', 'pm_score': 5, 'selected': False, 'text': '<p>I stumbled upon this question and i\'d like to share a snippet of code i currently use:</p>\n\n<pre><code>$.fn.exists = function(callback) {\n    var self = this;\n    var wrapper = (function(){\n            function notExists () {}\n\n            notExists.prototype.otherwise = function(fallback){\n                if (!self.length) {                    \n                    fallback.call();\n                }\n            };\n\n            return new notExists;\n        })();\n\n    if(self.length) {\n        callback.call();    \n    }\n\n    return wrapper;\n}\n</code></pre>\n\n<p>And now i can write code like this - </p>\n\n<pre><code>$("#elem").exists(function(){\n    alert ("it exists");\n}).otherwise(function(){\n    alert ("it doesn\'t exist");\n});\n</code></pre>\n\n<p>It might seem a lot of code, but when written in CoffeeScript it is quite small:</p>\n\n<pre><code>$.fn.exists = (callback) -&gt;\n    exists = @length\n    callback.call() if exists        \n    new class\n       otherwise: (fallback) -&gt;            \n            fallback.call() if not exists\n</code></pre>\n'}, {'answer_id': 25254106, 'author': 'technosaurus', 'author_id': 1162141, 'author_profile': 'https://Stackoverflow.com/users/1162141', 'pm_score': 6, 'selected': False, 'text': '<p>The reason all of the previous answers require the <code>.length</code> parameter is that they are mostly using jquery\'s <code>$()</code> 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 <strong>all</strong> matches to that selector and populating an array with them.</p>\n\n<p>The [\'length\'] parameter is not needed or useful and the code will be a lot faster if you directly use <code>document.querySelector(selector)</code> instead, because it returns the first element it matches or null if not found.</p>\n\n<pre><code>function elementIfExists(selector){  //named this way on purpose, see below\n    return document.querySelector(selector);\n}\n/* usage: */\nvar myelement = elementIfExists("#myid") || myfallbackelement;\n</code></pre>\n\n<p>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).</p>\n\n<pre><code>var myel=elementIfExists("#myid");\n// now we are using a reference to the element which will linger after removal\nmyel.getParentNode.removeChild(myel);\nconsole.log(elementIfExists("#myid")); /* null */\nconsole.log(myel); /* giant table lingering around detached from document */\nmyel=null; /* now it can be garbage collected */\n</code></pre>\n\n<p>In some cases this may be desired.  It can be used in a for loop like this:</p>\n\n<pre><code>/* locally scoped myel gets garbage collected even with the break; */\nfor (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))\n    if (myel == myblacklistedel) break;\n</code></pre>\n\n<p>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?</p>\n\n<pre><code>function elementExists(selector){\n    return !!document.querySelector(selector);\n}\n/* usage: */\nvar hastables = elementExists("table");  /* will be true or false */\nif (hastables){\n    /* insert css style sheet for our pretty tables */\n}\nsetTimeOut(function (){if (hastables &amp;&amp; !elementExists("#mytablecss"))\n                           alert("bad table layouts");},3000);\n</code></pre>\n'}, {'answer_id': 30022188, 'author': 'Santiago Hernández', 'author_id': 4343318, 'author_profile': 'https://Stackoverflow.com/users/4343318', 'pm_score': 5, 'selected': False, 'text': '<p>this is very similar to all of the answers, but why not use the <code>!</code> operator twice so you can get a boolean:</p>\n\n<pre><code>jQuery.fn.exists = function(){return !!this.length};\n\nif ($(selector).exists()) {\n    // the element exists, now what?...\n}\n</code></pre>\n'}, {'answer_id': 31317777, 'author': 'Anurag Deokar', 'author_id': 3458967, 'author_profile': 'https://Stackoverflow.com/users/3458967', 'pm_score': 6, 'selected': False, 'text': '<p>You can check element is present or not using length in java script.\n   If length is greater than zero then element is present if length is zero then\n   element is not present   </p>\n\n<pre><code>// These by Id\nif ($("#elementid").length &gt; 0) {\n  // Element is Present\n} else {\n  // Element is not Present\n}\n\n// These by Class\nif ($(".elementClass").length &gt; 0) {\n  // Element is Present\n} else {\n  // Element is not Present\n}\n</code></pre>\n'}, {'answer_id': 31900459, 'author': 'guest271314', 'author_id': 2801559, 'author_profile': 'https://Stackoverflow.com/users/2801559', 'pm_score': 5, 'selected': False, 'text': '<p>Try testing for <code>DOM</code> element</p>\n\n<pre><code>if (!!$(selector)[0]) // do stuff\n</code></pre>\n'}, {'answer_id': 33111577, 'author': 'Oliver', 'author_id': 177710, 'author_profile': 'https://Stackoverflow.com/users/177710', 'pm_score': 5, 'selected': False, 'text': '<p>Inspired by <a href="https://stackoverflow.com/a/19533724/177710">hiway\'s answer</a> I came up with the following:</p>\n\n<pre><code>$.fn.exists = function() {\n    return $.contains( document.documentElement, this[0] );\n}\n</code></pre>\n\n<p><a href="http://api.jquery.com/jQuery.contains/" rel="noreferrer">jQuery.contains</a> takes two DOM elements and checks whether the first one contains the second one.</p>\n\n<p>Using <code>document.documentElement</code> as the first argument fulfills the semantics of the <code>exists</code> method when we want to apply it solely to check the existence of an element in the current document.</p>\n\n<p>Below, I\'ve put together a snippet that compares <code>jQuery.exists()</code> against the <code>$(sel)[0]</code> and <code>$(sel).length</code> approaches which both return <code>truthy</code> values for <code>$(4)</code> while <code>$(4).exists()</code> returns <code>false</code>. In the context of <strong>checking for existence</strong> of an element in the DOM this seems to be the <strong>desired result</strong>.</p>\n\n<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">\r\n<div class="snippet-code snippet-currently-hidden">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>$.fn.exists = function() {\r\n    return $.contains(document.documentElement, this[0]); \r\n  }\r\n  \r\n  var testFuncs = [\r\n    function(jq) { return !!jq[0]; },\r\n    function(jq) { return !!jq.length; },\r\n    function(jq) { return jq.exists(); },\r\n  ];\r\n    \r\n  var inputs = [\r\n    ["$()",$()],\r\n    ["$(4)",$(4)],\r\n    ["$(\'#idoexist\')",$(\'#idoexist\')],\r\n    ["$(\'#idontexist\')",$(\'#idontexist\')]\r\n  ];\r\n  \r\n  for( var i = 0, l = inputs.length, tr, input; i &lt; l; i++ ) {\r\n    input = inputs[i][1];\r\n    tr = "&lt;tr&gt;&lt;td&gt;" + inputs[i][0] + "&lt;/td&gt;&lt;td&gt;"\r\n          + testFuncs[0](input) + "&lt;/td&gt;&lt;td&gt;"\r\n          + testFuncs[1](input) + "&lt;/td&gt;&lt;td&gt;"\r\n          + testFuncs[2](input) + "&lt;/td&gt;&lt;/tr&gt;";\r\n    $("table").append(tr);\r\n  }</code></pre>\r\n<pre class="snippet-code-css lang-css prettyprint-override"><code>td { border: 1px solid black }</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;\r\n&lt;div id="idoexist"&gt;#idoexist&lt;/div&gt;\r\n&lt;table style&gt;\r\n&lt;tr&gt;\r\n  &lt;td&gt;Input&lt;/td&gt;&lt;td&gt;!!$(sel)[0]&lt;/td&gt;&lt;td&gt;!!$(sel).length&lt;/td&gt;&lt;td&gt;$(sel).exists()&lt;/td&gt;\r\n&lt;/tr&gt;\r\n&lt;/table&gt;\r\n&lt;script&gt;\r\n  \r\n  $.fn.exists = function() {\r\n    return $.contains(document.documentElement, this[0]); \r\n  }\r\n  \r\n&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 35873574, 'author': 'ducdhm', 'author_id': 1330990, 'author_profile': 'https://Stackoverflow.com/users/1330990', 'pm_score': 4, 'selected': False, 'text': "<p>Here is my favorite <code>exist</code> method in jQuery</p>\n\n<pre><code>$.fn.exist = function(callback) {\n    return $(this).each(function () {\n        var target = $(this);\n\n        if (this.length &gt; 0 &amp;&amp; typeof callback === 'function') {\n            callback.call(target);\n        }\n    });\n};\n</code></pre>\n\n<p>and other version which supports callback when selector does not exist</p>\n\n<pre><code>$.fn.exist = function(onExist, onNotExist) {\n    return $(this).each(function() {\n        var target = $(this);\n\n        if (this.length &gt; 0) {\n            if (typeof onExist === 'function') {\n                onExist.call(target);\n            }\n        } else {\n            if (typeof onNotExist === 'function') {\n                onNotExist.call(target);\n            }\n        }\n    });\n};\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$('#foo .bar').exist(\n    function () {\n        // Stuff when '#foo .bar' exists\n    },\n    function () {\n        // Stuff when '#foo .bar' does not exist\n    }\n);\n</code></pre>\n"}, {'answer_id': 36218739, 'author': 'Kamuran Sönecek', 'author_id': 4766521, 'author_profile': 'https://Stackoverflow.com/users/4766521', 'pm_score': 4, 'selected': False, 'text': '<p><code>$("selector"</code>) returns an object which has the <code>length</code> 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 <code>0 == false</code>, so if you don\'t get <code>0</code> your code will run.</p>\n\n<pre><code>if($("selector").length){\n   //code in the case\n} \n</code></pre>\n'}, {'answer_id': 37902260, 'author': 'Sanu Uthaiah Bollera', 'author_id': 2804790, 'author_profile': 'https://Stackoverflow.com/users/2804790', 'pm_score': 5, 'selected': False, 'text': '<p>I just like to use plain vanilla javascript to do this.</p>\n\n<pre><code>function isExists(selector){\n  return document.querySelectorAll(selector).length&gt;0;\n}\n</code></pre>\n'}, {'answer_id': 38581695, 'author': 'Sunil Kumar', 'author_id': 6116564, 'author_profile': 'https://Stackoverflow.com/users/6116564', 'pm_score': 4, 'selected': False, 'text': '<p>Yes The best method of doing this :</p>\n\n<p>By <code>JQuery</code> :</p>\n\n<pre><code>if($("selector").length){\n   //code in the case\n}\n</code></pre>\n\n<p><code>selector</code> can be <code>Element</code> <code>ID</code> OR <code>Element</code> <code>Class</code></p>\n\n<p>OR</p>\n\n<p>If you don\'t want to use <code>jQuery</code> Library then you can achieve this by using Core <code>JavaScript</code> :</p>\n\n<p>By <code>JavaScript</code> :</p>\n\n<pre><code>if(document.getElementById("ElementID")) {\n    //Do something...\n}\n</code></pre>\n'}, {'answer_id': 38681468, 'author': 'abhirathore2006', 'author_id': 1785635, 'author_profile': 'https://Stackoverflow.com/users/1785635', 'pm_score': 4, 'selected': False, 'text': '<p>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.</p>\n<pre><code>var a = null;\n\nvar b = []\n\nvar c = undefined ;\n\nif(a) { console.log(&quot; a exist&quot;)} else { console.log(&quot;a doesn\'t exit&quot;)}\n// output: a doesn\'t exit\n\nif(b) { console.log(&quot; b exist&quot;)} else { console.log(&quot;b doesn\'t exit&quot;)}\n// output: b exist\n\nif(c) { console.log(&quot; c exist&quot;)} else { console.log(&quot;c doesn\'t exit&quot;)}\n// output: c doesn\'t exit\n</code></pre>\n<p><strong>FINAL SOLUTION</strong></p>\n<pre><code>if($(&quot;#xysyxxs&quot;).length){ console.log(&quot;xusyxxs exist&quot;)} else { console.log(&quot;xusyxxs doesnn\'t exist&quot;) }\n//output : xusyxxs doesnn\'t exist\n\nif($(&quot;.xysyxxs&quot;).length){ console.log(&quot;xusyxxs exist&quot;)} else { console.log(&quot;xusyxxs doesnn\'t exist&quot;) }\n    //output : xusyxxs doesnn\'t exist\n</code></pre>\n<h2>Demo</h2>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log("existing id", $(\'#id-1\').length)\nconsole.log("non existing id", $(\'#id-2\').length)\n\nconsole.log("existing class single instance", $(\'.cls-1\').length)\nconsole.log("existing class multiple instance", $(\'.cls-2\').length)\nconsole.log("non existing class", $(\'.cls-3\').length)</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;\n&lt;div id="id-1"&gt;\n  &lt;div class="cls-1 cls-2"&gt;&lt;/div&gt;\n  &lt;div class="cls-2"&gt;&lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 39102819, 'author': 'Jonathan Cardoz', 'author_id': 4098272, 'author_profile': 'https://Stackoverflow.com/users/4098272', 'pm_score': -1, 'selected': False, 'text': '<p>Use the following syntax to check if the element actually exists using jQuery.</p>\n\n<pre><code>let oElement = $(".myElementClass");\nif(oElement[0]) {\n    // Do some jQuery operation here using oElement\n}\nelse {\n    // Unable to fetch the object\n}\n</code></pre>\n'}, {'answer_id': 40842324, 'author': 'Pawel', 'author_id': 696535, 'author_profile': 'https://Stackoverflow.com/users/696535', 'pm_score': 5, 'selected': False, 'text': '<p>No need for jQuery (basic solution)</p>\n<pre><code>if(document.querySelector(\'.a-class\')) {\n  // do something\n}\n</code></pre>\n<p>Much more performant option below (notice the lack of a dot before <code>a-class</code>).</p>\n<pre><code>if(document.getElementsByClassName(\'a-class\')[0]) {\n  // do something\n}\n</code></pre>\n<p><code>querySelector</code> uses a proper matching engine like <code>$()</code> (sizzle) in jQuery and uses more computing power but in 99% of cases will do just fine. The second option is more explicit and tells the code exactly what to do. It\'s much faster according to JSBench <a href="https://jsbench.me/65l2up3t8i" rel="nofollow noreferrer">https://jsbench.me/65l2up3t8i</a></p>\n'}, {'answer_id': 42954642, 'author': 'Tilak Madichetti', 'author_id': 4546390, 'author_profile': 'https://Stackoverflow.com/users/4546390', 'pm_score': 5, 'selected': False, 'text': '<p><a href="https://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/" rel="noreferrer">Checking for existence of an element</a> is documented neatly in the official jQuery website itself!</p>\n\n<blockquote>\n  <p>Use the <a href="https://api.jquery.com/length/" rel="noreferrer">.length</a> property of the jQuery collection returned by your\n  selector:</p>\n\n<pre><code>if ($("#myDiv").length) {\n    $("#myDiv").show();\n}\n</code></pre>\n  \n  <p>Note that it isn\'t always necessary to test whether an element exists.\n  The following code will show the element if it exists, and do nothing\n  (with no errors) if it does not:</p>\n\n<pre><code>$("#myDiv").show();\n</code></pre>\n</blockquote>\n'}, {'answer_id': 44084113, 'author': 'Alireza', 'author_id': 5423108, 'author_profile': 'https://Stackoverflow.com/users/5423108', 'pm_score': 6, 'selected': False, 'text': "<p>I see most of the answers here are <strong>not accurate</strong> as they should be, they check element length, it can be <strong>OK</strong> in many cases, but <strong>not 100%</strong>, 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:</p>\n\n<pre><code>$.fn.exists = $.fn.exists || function() { \n  return !!(this.length &amp;&amp; (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); \n}\n</code></pre>\n\n<p>This will check both length and type, Now you can check it this way:</p>\n\n<pre><code>$(1980).exists(); //return false\n$([1,2,3]).exists(); //return false\n$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false\n$([{nodeName: 'foo'}]).exists() // returns false\n$('div').exists(); //return true\n$('.header').exists(); //return true\n$(document).exists(); //return true\n$('body').exists(); //return true\n</code></pre>\n"}, {'answer_id': 44649473, 'author': 'Andrei Todorut', 'author_id': 6318702, 'author_profile': 'https://Stackoverflow.com/users/6318702', 'pm_score': 4, 'selected': False, 'text': "<p>You don't have to check if it's greater than <code>0</code> like <code>$(selector).length &gt; 0</code>, <code>$(selector).length</code> it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.</p>\n<pre><code>if($(selector).length){\n  // true if length is not 0\n} else {\n  // false if length is 0\n}\n</code></pre>\n"}, {'answer_id': 46772630, 'author': 'sina_Islam', 'author_id': 1657994, 'author_profile': 'https://Stackoverflow.com/users/1657994', 'pm_score': 3, 'selected': False, 'text': '<p>A simple utility function for both id and class selector.</p>\n\n<pre><code>function exist(IdOrClassName, IsId) {\n  var elementExit = false;\n  if (IsId) {\n    elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;\n  } else {\n    elementExit = $("." + "" + IdOrClassName + "").length ? true : false;\n  }\n  return elementExit;\n}\n</code></pre>\n\n<p>calling this function like bellow </p>\n\n<pre><code>$(document).ready(function() {\n  $("#btnCheck").click(function() {\n    //address is the id so IsId is true. if address is class then need to set IsId false\n    if (exist("address", true)) {\n      alert("exist");\n    } else {\n      alert("not exist");\n    }\n  });\n});\n</code></pre>\n'}, {'answer_id': 49332073, 'author': 'Jonas Lundman', 'author_id': 2445357, 'author_profile': 'https://Stackoverflow.com/users/2445357', 'pm_score': 3, 'selected': False, 'text': '<p>All answers is <em>not</em> working <strong>bullet proof</strong> to check existence of an element in jQuery. After many years of coding, only this solution does not throw any warnings about existance or not:</p>\n\n<pre><code>if($(selector).get(0)) { // Do stuff }\n</code></pre>\n\n<p>Or to bail instead in the beginning of your function:</p>\n\n<pre><code>if(!$(selector).get(0)) return;\n</code></pre>\n\n<p><strong>Explained</strong></p>\n\n<p>In this case, you dont have to deal with zero | null lengths issues. This forces to fetch an element, not count them.</p>\n'}, {'answer_id': 51877072, 'author': 'Manish Vadher', 'author_id': 6313628, 'author_profile': 'https://Stackoverflow.com/users/6313628', 'pm_score': 0, 'selected': False, 'text': "<p>The input won't have a value if it doesn't exist. Try this...</p>\n\n<pre><code>if($(selector).val())\n</code></pre>\n"}, {'answer_id': 51905917, 'author': 'Hassan Sadeghi', 'author_id': 9881249, 'author_profile': 'https://Stackoverflow.com/users/9881249', 'pm_score': 4, 'selected': False, 'text': '<p>Try this.</p>\n\n<p><strong>simple</strong> and <strong>short</strong> and <strong>usable in the whole project</strong>:</p>\n\n<pre><code>jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>console.log($("element-selector").exists());\n</code></pre>\n\n<p><strong>_________________________________</strong></p>\n\n<p><strong>OR EVEN SHORTER</strong>:\n(<strong>for when</strong> you don\'t want to define a jQuery plugin):</p>\n\n<pre><code>if(!!$("elem-selector")[0]) ...;\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>if($("elem-selector")[0]) ...;\n</code></pre>\n'}, {'answer_id': 51990277, 'author': 'Rafal Enden', 'author_id': 3042543, 'author_profile': 'https://Stackoverflow.com/users/3042543', 'pm_score': -1, 'selected': False, 'text': "<p>Use <code>querySelectorAll</code> with <code>forEach</code>, no need for <code>if</code> and extra assignment:</p>\n\n<pre><code>document.querySelectorAll('.my-element').forEach((element) =&gt; {\n  element.classList.add('new-class');\n});\n</code></pre>\n\n<p>as the opposite to:</p>\n\n<pre><code>const myElement = document.querySelector('.my-element');\nif (myElement) {\n  element.classList.add('new-class');\n}\n</code></pre>\n"}, {'answer_id': 53844610, 'author': 'Abdul Rahman', 'author_id': 1821361, 'author_profile': 'https://Stackoverflow.com/users/1821361', 'pm_score': 3, 'selected': False, 'text': '<p>I am using this:</p>\n\n<pre><code> if($("#element").length &gt; 0){\n   //the element exists in the page, you can do the rest....\n }\n</code></pre>\n\n<p>Its very simple and easy to find an element.</p>\n'}, {'answer_id': 53865043, 'author': 'Majedur', 'author_id': 3915410, 'author_profile': 'https://Stackoverflow.com/users/3915410', 'pm_score': 3, 'selected': False, 'text': "<p>Just check the length of the selector, if it more than 0 then it's return true otherwise false.</p>\n\n<p>For ID:</p>\n\n<pre><code> if( $('#selector').length )         // use this if you are using id to check\n{\n     // it exists\n}\n</code></pre>\n\n<p>For Class:</p>\n\n<pre><code> if( $('.selector').length )         // use this if you are using class to check\n{\n     // it exists\n}\n</code></pre>\n\n<p>For Dropdown:</p>\n\n<pre><code>if( $('#selector option').size() ) {   // use this if you are using dropdown size to check\n\n   // it exists\n}\n</code></pre>\n"}, {'answer_id': 58439064, 'author': 'chickens', 'author_id': 1602301, 'author_profile': 'https://Stackoverflow.com/users/1602301', 'pm_score': 2, 'selected': False, 'text': '<p>With jQuery you do not need <code>&gt;0</code>, this is all you need:</p>\n\n<pre><code>if ($(selector).length)\n</code></pre>\n\n<p>With vanilla JS, you can do the same with:</p>\n\n<pre><code>if(document.querySelector(selector))\n</code></pre>\n\n<p>If you want to turn it into a function that returns bool:</p>\n\n<pre><code>const exists = selector =&gt; !!document.querySelector(selector);\n\nif(exists(selector)){\n  // some code\n}\n</code></pre>\n'}, {'answer_id': 60629417, 'author': 'Amit Sharma', 'author_id': 6827830, 'author_profile': 'https://Stackoverflow.com/users/6827830', 'pm_score': 3, 'selected': False, 'text': "<p>By default - No.</p>\n<p>There's the <code>length</code> property that is commonly used for the same result in the following way:</p>\n<pre><code>if ($(selector).length)\n</code></pre>\n<p>Here, 'selector' is to be replaced by the actual selector you are interested to find if it exists or not. If it does exist, the length  property will output an integer more than 0 and hence the <code>if</code> statement will become true and hence execute the if block. If it doesn't, it will output the integer '0' and hence the if block won't get executed.</p>\n"}, {'answer_id': 64024660, 'author': 'Greedo', 'author_id': 11829408, 'author_profile': 'https://Stackoverflow.com/users/11829408', 'pm_score': 2, 'selected': False, 'text': '<p>I found that this is the most <em>jQuery way</em>, IMHO.\nExtending the default function is easy and can be done in a global extension file.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>$.fn.exist = function(){\n  return !!this.length;\n};\n\nconsole.log($("#yes").exist())\n\nconsole.log($("#no").exist())</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;\n\n&lt;div id="yes"&gt;id = yes&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 66033686, 'author': 'Gareth Compton', 'author_id': 4892181, 'author_profile': 'https://Stackoverflow.com/users/4892181', 'pm_score': 1, 'selected': False, 'text': '<p>There is an oddity known as short circuit conditioning.  Not many are making this feature known so allow me to explain! &lt;3</p>\n<pre><code>//you can check if it isnt defined or if its falsy by using OR\nconsole.log( $(selector) || \'this value doesnt exist\' )\n\n//or run the selector if its true, and ONLY true\nconsole.log( $(selector) &amp;&amp; \'this selector is defined, now lemme do somethin!\' )\n\n//sometimes I do the following, and see how similar it is to SWITCH\nconsole.log(\n({  //return something only if its in the method name\n    \'string\':\'THIS is a string\',\n    \'function\':\'THIS is a function\',\n    \'number\':\'THIS is a number\',\n    \'boolean\':\'THIS is a boolean\'\n})[typeof $(selector)]||\n//skips to this value if object above is undefined\n\'typeof THIS is not defined in your search\')\n</code></pre>\n<p>The last bit allows me to see what kind of input my typeof has, and runs in that list.  If there is a value outside of my list, I use the <code>OR (||)</code> operator to skip and nullify.  This has the same performance as a <code>Switch Case</code> and is considered somewhat concise. <a href="https://measurethat.net/Benchmarks/Show/10837/0/conditionals-if-else-ternary-switch-object-function-obj" rel="nofollow noreferrer">Test Performance of the conditionals and uses of logical operators</a>.</p>\n<p>Side note: The Object-Function kinda has to be rewritten &gt;.&lt;\' But this test I built was made to look into concise and expressive conditioning.</p>\n<p>Resources:\n<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND" rel="nofollow noreferrer">Logical AND (with short circuit evaluation)</a></p>\n'}, {'answer_id': 70234944, 'author': 'Haroon Fayyaz', 'author_id': 13380986, 'author_profile': 'https://Stackoverflow.com/users/13380986', 'pm_score': 1, 'selected': False, 'text': '<p>Thanks for sharing this question. First of all, there are multiple ways to check it.\nIf you want to check whether an <code>HTML</code> element exists in <code>DOM</code>. To do so you can try the following ways.</p>\n<ol>\n<li>Using <code>Id</code> selector: In DOM to select element by <code>id</code>, you should provide the name of the id starting with the prefix <code>(#)</code>. You have to make sure that each Html element in the DOM must have unique <code>id</code>.</li>\n<li>Using <code>class</code> selector: You can select all elements with belonging to a specific class by using the prefix <code>(.)</code>.</li>\n</ol>\n<p>Now if you want to check if the element exist or not in DOM you can check it using the following code.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>if($("#myId").length){\n   //id selector\n} \n\nif($(".myClass").length){\n   //class selector\n} </code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you want to check any variable is undefined or not. You can check it using the following code.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>let x\nif(x)\n  console.log("X");\nelse\n  console.log("X is not defined");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 70245882, 'author': 'Vishwesh Chotaliya', 'author_id': 15483583, 'author_profile': 'https://Stackoverflow.com/users/15483583', 'pm_score': 3, 'selected': False, 'text': "<p><strong>In Javascript</strong></p>\n<pre><code>if (typeof selector != &quot;undefined&quot;) {\n   console.log(&quot;selector exists&quot;);\n} else {\n   console.log(&quot;selector does not exists&quot;);\n}\n</code></pre>\n<p><strong>In jQuery</strong></p>\n<pre><code>if($('selector').length){\n    alert(&quot;selector exists&quot;);\n} else{\n    alert(&quot;selector does not exists&quot;);\n}\n</code></pre>\n"}, {'answer_id': 73512301, 'author': 'Vladislav Ladicky', 'author_id': 9805590, 'author_profile': 'https://Stackoverflow.com/users/9805590', 'pm_score': 0, 'selected': False, 'text': '<p>No, there is no such a method. But you can extend jQuery for your own one. Current way (2022) to do that is:</p>\n<pre><code>jQuery.fn.extend({\n  exists() { return !!this.length }\n});\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/31044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302/']