суббота, 23 апреля 2011 г.

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.
  1. if($("#id") != null)  
  2. {  
  3. //Write code if the object is not null  
  4. }  
  5.   
  6. if($(".class") != null)  
  7. {  
  8. //Write code if the object is not null  
  9. }  
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,
  1. if($("#id").length > 0)  
  2. {  
  3. //Write code if the object is not null  
  4. }  
  5.   
  6. if($(".class").length > 0)  
  7. {  
  8. //Write code if the object is not null  
  9. }  
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?

Комментариев нет: