jQuery – Correct way to check if object is null or Empty

jQuery – Correct way to check if object is null or Empty

Yesterday, I ran into a interesting and frustrating situation where for couple of minutes I was not able to find out what’s wrong with my code. But I learned something new. Let me first give you an idea about what I was working on. I was creating a function, which first checks of div element object. If not found, then create a new div element and insert in DOM otherwise just update the html of div.
Below is the jQuery code.

01 $(document).ready(function () {
02     function UpdateHTML()
03     {
04         var $dvElement = $('#dvElement');
05         if (!$dvElement)
06         {
07             $("<div />", {
08                 id: 'dvElement',
09                 html: 'Added Just now'
10             }).appendTo('body');
11         }
12         else
13             $dvElement.html('Updated HTML');
14     }
15 });

When this function is called, it does nothing. In the first call, it should create a div but it was not. When I debugged, I found that it is always going in else part of the condition. The condition (!$dvElement) always returning false. Wooo..Confused…
Every time when we pass a selector to jQuery function, it will always return a jQuery object. So whether the div exist or not, an object is returned. And when we test the jQuery object inside if statement, it will always be TRUE.
To fix the above code, we need to find out whether the object is empty. And there are 2 ways to fix this.

  • length property: Returns number of elements in object
  • $.isEmptyObject(Object): Returns true if the object doesn’t define any methods or properties.

So fix is,

01 $(document).ready(function () {
02     function UpdateHTML()
03     {
04         var $dvElement = $('#dvElement');
05         if (!$dvElement.length)  // OR !$.isEmptyObject($dvElement)
06         {
07             $("<div />", {
08                 id: 'dvElement',
09                 html: 'Added Just now'
10             }).appendTo('body');
11         }
12         else
13             $dvElement.html('Updated HTML');
14     }
15 });