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?
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?
Checking for existence of an element is documented neatly in the official jQuery website itself!
I just like to use plain vanilla javascript to do this.
There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:
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.
jQuery is really cool, but don't let pure JavaScript fall into oblivion...
Is
$.contains()
what you want?I have found
if ($(selector).length) {}
to be insufficient. It will silently break your app whenselector
is an empty object{}
.My only suggestion is to perform an additional check for
{}
.I'm still looking for a better solution though as this one is a bit heavy.
Edit: WARNING! This doesn't work in IE when
selector
is a string.