Friday 3 May 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...