Wednesday, 14 September 2011

More information on checking if an element exists in JQuery

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

}

No comments: