How can I check the existence of an element in jQuery?
The current code that I have is this:
JavaScript
x
4
1
if ($(selector).length > 0) {
2
// Do something
3
}
4
Is there a more elegant way to approach this? Perhaps a plugin or a function?
Advertisement
Answer
In JavaScript, everything is ‘truthy’ or ‘falsy’, and for numbers 0
means false
, everything else true
. So you could write:
JavaScript
1
2
1
if ($(selector).length)
2
You don’t need that >0
part.