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?
I'm using this:
Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/
$("selector"
) give an object which haslength
data. If there are elements as you define in selector, you will get them from the object. So if you check it's length you allready can find, is there any element exists. In javascript0 == false
alsonull == false
. If you not get0
your codes will run.If you used
you would imply that chaining was possible when it is not.
This would be better:
Alternatively, from the FAQ:
You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.
this is very similar to all of the answers, but why not use the
!
operator twice so you can get a boolean:Inspired by hiway's answer I came up with the following:
jQuery.contains takes two DOM elements and checks whether the first one contains the second one.
Using
document.documentElement
as the first argument fulfills the semantics of theexists
method when we want to apply it solely to check the existence of an element in the current document.Below, I've put together a snippet that compares
jQuery.exists()
against the$(sel)[0]
and$(sel).length
approaches which both returntruthy
values for$(4)
while$(4).exists()
returnsfalse
. In the context of checking for existence of an element in the DOM this seems to be the desired result.The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:
It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.
And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.
NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).