jQuery – Correct way to check if object is null or Empty
Related Post:
- OOPS!!!! jQuery Selectors NOT working...
- Ignored powerful shortcuts of jQuery
- jQuery code not working - A Daily Battle
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.