Skip to content

More information on checking if an element exists in JQuery

September 14, 2011

The simplest mistake sometimes costs several hours of debugging. One of these is checking if the target exists before trying to apply some changes to/using it.

How to check if element in DOM exists, i.e. if the selector $(‘.some_class’) is not empty?

The simplest:

if ($('.some_class')) {

//some action

}

will not work!

The correct condition uses the .length function:

if ($('.some_class').length > 0) {

//some action

}

Note no brackets after .length.

How to check if JavaScript object’s property exists?

This is tricky, as there are two types of properties: own properties and prototype properties. Not going into details, we can assume, that own properties are the one that are for example serialized by JSON, and prototype properties are the one that can be empty or not, but are given in the object’s definition.

So, in most cases you want to check if the own property exists for the given object. This can be obtained using the hasOwnProperty() method:

if (the_object.hasOwnProperty("name)) {

//some action

}

If you only want to check whether there is the prototype property, you may use in operator to determine the existence of the property:

if ("name" in the_object)) {

//some action

}

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: