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.

Related Post:

Below is the jQuery code.

$(document).ready(function () {
    function UpdateHTML() 
    {
        var $dvElement = $('#dvElement');
        if (!$dvElement) 
        {
            $("<div />", {
                id: 'dvElement',
                html: 'Added Just now'
            }).appendTo('body');
        } 
        else 
            $dvElement.html('Updated HTML');
    }
});

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,

$(document).ready(function () {
    function UpdateHTML() 
    {
        var $dvElement = $('#dvElement');
        if (!$dvElement.length)  // OR !$.isEmptyObject($dvElement)
        {
            $("<div />", {
                id: 'dvElement',
                html: 'Added Just now'
            }).appendTo('body');
        } 
        else 
            $dvElement.html('Updated HTML');
    }
});

So always use .length or $.isEmptyObject() function to find out whether object is empty, null or has some elements.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...