Saturday, March 9, 2013

jQuery - checking for "null" objects...

In day to day Object Oriented programming we used to check whether an object is null by comparing it with the null keyword supplied by the programming language. For an example in Java or javascripts we can use

1:  object == null  

So what we use to do with jQuery  is like below,

1:  $("#id") == null  

This is wrong. The reason is that even there is no any HTML elements that has id of "id", $("#id")  will return an empty object. (or empty array object,). So this will always make the above expression to evaluate to false.

So how we get to know whether above object (element) exist before using that object in complicate logic ???

You can use the following code.

1:  $("#id").length > 0  

Now where does this length property come to HTML element. The reason is jQuery objects wrap around DOM objects and they are having their own methods and attributes. When we accessing HTML elements using jQuery, it will return an array of such elements. So if there is only one object returned we can directly access that object. If there are more than one object we can use normal array indexes to access them. But if there is no object or 0 object for what we asked, what jQuery does is return an empty array object. So what we can do to check if there is no object relevant what we have asked is to check the length of the array return by jQuery. If length of the array is not greater than 0 means there is no object to be return (only the empty array object is there).