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?
javascriptjquery
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?
Best Answer
In JavaScript, everything is 'truthy' or 'falsy', and for numbers
0
meansfalse
, everything elsetrue
. So you could write:You don't need that
>0
part.