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?
Try testing for
DOM
elementHere is my favorite
exist
method in jQueryand other version which supports callback when selector does not exist
Example:
In JavaScript, everything is 'truthy' or 'falsy', and for numbers
0
(and NaN) meansfalse
, everything elsetrue
. So you could write:You don't need that
>0
part.Yes!
This is in response to: Herding Code podcast with Jeff Atwood
This plugin can be used in an
if
statement likeif ($(ele).exist()) { /* DO WORK */ }
or using a callback.Plugin
jsFiddle
You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does not exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does not exist. Of course, if it does exist, the first function will fire and the chain will continue.
Keep in mind that using the callback variant helps maintain chainability – the element is returned and you can continue chaining commands as with any other jQuery method!
Example Uses
You can check element is present or not using length in java script. If length is greater than zero then element is present if length is zero then element is not present