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?
How about:
It's very minimal and saves you having to enclose the selector with
$()
every time.You can use this:
You can use:
A little more elegant, perhaps.
No need for jQuery
I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..
You can save a few bytes by writing:
This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns
undefined
if there is no item at the specified index.