Sunday, January 24, 2010

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?

Categories: ,

6 comments:

  1. if($("#id").length) is enough

    ReplyDelete
  2. Yes, you are right. It just written for better readability and understanding.
    Thanks again.
    -Praveen.

    ReplyDelete
  3. thanks! exactly what i needed.
    may look simple, but there aren't as many clear posts about it out there - so thanks for the explanation!

    ReplyDelete
  4. there is a method called empty(), your solution does not work well.

    ReplyDelete
  5. Hello,
    Thanks for your comment. But, if you get me the case where this solution does not work well, I am gald to know.

    thanks
    -Praveen.

    ReplyDelete
  6. @Anonymous, empty() is not used for checking whether or not an element exists, it's used for deleting/emptying objects.

    ReplyDelete