Saturday, 23 January 2010

How to check JQuery object is null

This is simple and no need to write post for it. You may feel same right? But, this is the question I received from almost 10 people till now. So, I thought of writing a post on it. So that, it may help people who are looking for the same through out the world.

By default JQuery returns object when you declare $("$id") or $(".class"). If you write code for it as below, then that's wrong.

if($("#id") != null)
{
//Write code if the object is not null
}

if($(".class") != null)
{
//Write code if the object is not null
}

If you write the above code for checking null condition then if condition always success and will execute code inside of the if condition. So, the correct solution is,

if($("#id").length > 0)
{
//Write code if the object is not null
}

if($(".class").length > 0)
{
//Write code if the object is not null
}

It tries to find all objects which has the given id or class and if any exists then the length will be equal to the number of times the id or class occurred. So, if the length is zero then it's nothing but the id or class don't exist and the object is null.

Hope, this solved your problem and this is a new tip for today. Is this helpful?

No comments:

Post a Comment