How do I check if an element exists if the element is created by .append()
method?
$('elemId').length
doesn't work for me.
-
60`.length` works just fine, see here: http://jsfiddle.net/yahavbr/A9zW2/ if you did use `#` post your code and we'll see what you done wrong. – Shadow The GPT Wizard Jan 04 '11 at 13:26
-
1Use $('#selector').length and $('.selector').length for id and class selector. $('#selector option').size() to check dropdown size. – Majedur Dec 20 '18 at 08:43
8 Answers
$('elemId').length
doesn't work for me.
You need to put #
before element id:
$('#elemId').length
---^
With vanilla JavaScript, you don't need the hash (#
) e.g. document.getElementById('id_here')
, however when using jQuery, you do need to put hash to target elements based on id
just like CSS.

- 17,418
- 8
- 58
- 76

- 377,238
- 77
- 533
- 578
-
49CSS selectors are used therefore "#elementId" selects by element. "elementId" would actually select all emenets whose _tags_ are named "elementId" – Petr Gladkikh Dec 13 '12 at 07:13
-
8@trejder Most likely the poster was unaware of Vanilla JS and when they said "vanilla JavaScript" they actually *meant* base JavaScript ("vanilla" as in "plain", "unadorned). – Chiara Coetzee Dec 12 '13 at 22:40
-
5@trejder Looks like "Vanilla JS" is exactly the same as base Javascript anyway (the downloaded file is always empty) - someone just decided to make a sales pitch for base Javascript. – Brilliand Jan 06 '14 at 17:59
-
8Yeah, that website is mocking the need for a framework called "Vanilla JS" which is nothing but JavaScript itself. @trejder should read a little more carefully. – LasagnaAndroid Mar 04 '14 at 21:47
-
3You "don't need the hash" only if you use the wrong function. `document.querySelector('#id_here')` requires the hash sign just as much as the jQuery equivalent `$('#id_here')`. – AndreKR Aug 08 '15 at 05:41
-
-
I really dislike this answer because it doesn't directly answer the question. – Kellen Stuart Apr 02 '19 at 14:58
-
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}

- 16,613
- 4
- 34
- 55

- 6,719
- 1
- 24
- 25
-
28I find this approach to be so unintuitive. It's almost like asking how to determine if a number is negative, and then someone telling you that you need to write the code in assembly and then manually twiddle some bits in the CPU's registers, instead of simply calling a method like .isNegative(). Checking the value of a 'length' property clutters things up. I'd rather see something like a .exists() method, which is instantly recognizable while scanning through code. – Aquarelle Jul 22 '14 at 20:08
-
3in some ways, jquery made leaps and bounds for making javascript more accessible, but is still very far from being idiomatic – random-forest-cat Sep 05 '14 at 03:45
-
4This solution is perfectly intuitive. The length property tells you how many elements match the query. What is not intuitive or straight-forward about that? – Alice Wonder Nov 07 '16 at 21:01
-
3You could just write a more intuitive function:`function exists(elementName) { return $(elementName).length; }` – Sinister Beard Feb 15 '17 at 11:21
-
This throws an exception in the console. `jquery.min.js:2 jQuery.Deferred exception: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined` – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Apr 12 '21 at 12:22
Try this:
if ($("#mydiv").length > 0){
// do something here
}
The length property will return zero if element does not exists.
-
34
-
I can't get this to work without including `> 0`. Any ideas why that might happen? – KillahB Aug 01 '17 at 06:03
-
-
@wessamelmahdy verbosity can increase clarity, which can reduce the cognitive cost of maintenance – BLAZORLOVER Nov 17 '21 at 13:05
-
1
How do I check if an element exists
if ($("#mydiv").length){ }
If it is 0
, it will evaluate to false
, anything more than that true
.
There is no need for a greater than, less than comparison.

- 33,652
- 11
- 120
- 99
-
-
-
thanks, no problem anymore. I have replace it with this one http://stackoverflow.com/a/21801090/2232458 – Ari Oct 04 '14 at 02:44
your elemId
as its name suggests, is an Id
attribute, these are all you can do to check if it exists:
Vanilla JavaScript: in case you have more advanced selectors:
//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}

- 12,723
- 6
- 28
- 35
-
You don't need `!= null` as `querySelector` will always return `null` (which is falsey) or an element – 1j01 Jun 21 '15 at 22:05
-
I would still use ```if (document.querySelector("elemId") != null )``` just to improve code readability – Mrinmoy Nov 30 '17 at 20:00
-
1@Mrinmoy your mindset is either coming from Java or C#. In JavaScript we know we have seven falsy values (0, -0, null, undefined, '', NaN and false) and considering those falsy values `if (document.querySelector("elemId") != null )` has no effect in writing a more readable code. In JavaScript world instead of keeping your mindset from structural programming languages like Java or C# it is highly recommended to get to know the conventions of JavaScript community. For a JavaScript developer in this specific case `!= null` is totally redundant and much less readable. – Mehran Hatami Nov 30 '17 at 21:39
-
@MehranHatami , so you are agreeing that the code is readable only by a javaScripter, still he will be left confused if ```querySelector()``` returns ```null or 0``` or any of the other 5 values. ```querySelectorAll() ``` and jQuery has a different return value when it dont find an element. Please consider that people these days work on polyglot of techs and frameworks so making things more readable is sure to benefit. By the way I am more a javascripter than a java/golang programmer – Mrinmoy Dec 18 '17 at 22:45
-
@Mrinmoy I agree that this is a debatable topic BUT what I said was not my opinion than a fact. in my team, if I see a pull request which has ` != null ` I don't approve it. Although it is a convention BUT it has become a rule, sort of. To me what matters the most is to make sure the developer in my team knows the basics and their code is consistent with no redundancy. ` != null` to me is like ` != false` which is a valid condition for an if statement BUT it redundant in itself. – Mehran Hatami Dec 19 '17 at 10:12
-
@Mrinmoy in JavaScript when we say `if (a){}` it means `a` exists or is not falsy and comparing it with null is valid ONLY when you want to validate the value to be specifically `null` which is not the case in this example. You are free to use both BUT I wouldn't approve it if any of my developers use ` != null` for this kind of cases, which means its being a convention has some effect in making it more or less readable. – Mehran Hatami Dec 19 '17 at 10:13
-
@MehranHatami so did you invented any linter rule which look for ```!= null``` or can you point me to any famous linters that have this condition baked in. if I use ```!== null``` what wud you do? JS has a strict type checks, would you advise against using it? there are functions that returns ```null, 0 or undefined``` and each implies a different reason so ```if (a){ }``` wont cut for all the cases. plus its a good thing to educate ur developers on what the function is returning rather than leaving them with a guess work to figure out which falsy or non-falsy value they are dealing with – Mrinmoy Dec 30 '17 at 07:29
You can also use array-like notation and check for the first element.
The first element of an empty array or collection is simply undefined
, so you get the "normal" javascript truthy/falsy behaviour:
var el = $('body')[0];
if (el) {
console.log('element found', el);
}
if (!el) {
console.log('no element found');
}

- 617
- 8
- 14
You can use native JS to test for the existence of an object:
if (document.getElementById('elemId') instanceof Object){
// do something here
}
Don't forget, jQuery is nothing more than a sophisticated (and very useful) wrapper around native Javascript commands and properties

- 10,007
- 11
- 42
- 64

- 844
- 7
- 7
If you have a class on your element, then you can try the following:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}

- 12,622
- 16
- 73
- 101

- 139
- 2
- 2
-
14
-
2
-
This answer should get a golden badge for the most funniest answer of SO :)) – Mohsen Jun 16 '20 at 14:35
-