How can we check the existence of an element in jQuery?
The current code that we have is this:
Is there is a more elegant way to approach this? Perhaps a plugin or a function?
If we used
- we would imply that chaining was possible when it is not.
- This would be better:
We 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.
We can use this:
We 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.