This question already has an answer here:
- Is there an “exists” function for jQuery? 40 answers
How do I check if an element exists if the element is created by .append()
method?
$('elemId').length
doesn't work for me.
This question already has an answer here:
How do I check if an element exists if the element is created by .append()
method?
$('elemId').length
doesn't work for me.
If you have a class on your element, then you can try the following:
You can use native JS to test for the existence of an object:
Don't forget, jQuery is nothing more than a sophisticated (and very useful) wrapper around native Javascript commands and properties
If it is
0
, it will evaluate tofalse
, anything more than thattrue
.There is no need for a greater than, less than comparison.
Try this:
The length property will return zero if element does not exists.
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:your
elemId
as its name suggests, is anId
attribute, these are all you can do to check if it exists:Vanilla JavaScript: in case you have more advanced selectors:
jQuery: