Friday, May 3, 2019

javascript - Is there an "exists" function for jQuery?




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?


Answer



In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 (and NaN) means false, everything else true. So you could write:



if ($(selector).length)


You don't need that >0 part.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...