HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Is there an "exists" function for jQuery?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
functionjqueryexistsforthere

Problem

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?

Solution

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

if ($(selector).length)


You don't need that >0 part.

Code Snippets

if ($(selector).length)

Context

Stack Overflow Q#31044, score: 2775

Revisions (0)

No revisions yet.