javascript tutorial - [Solved-5 Solutions] Exists function for jQuery - javascript - java script - javascript array
Problem:
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?
Solution 1:
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 (and NaN) means false, everything else true. So we could write: if ($(selector).length) We don't need that >0 part.
Solution 2:
Solution 3:
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.
Solution 4:
We can use this:
Solution 5:
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.