jQuery Tip - How to check if element is empty

In this post, I will show you a simple tip to check or verify that the element that you are accessing in jQuery is empty or not. jQuery provides a method to get and set html of any control. Check these articles for more details.


Earlier I had posted about How to check element visible or hidden using jQuery, Difference between empty() vs remove() and Don't use jQuery.size() to count number of element. And in this post, find jQuery way to check if element is empty.

We will use the same html() attribute to determine whether the element is empty or not.
$(document).ready(function() {
  if ($('#dvText').html()) {
    alert('Proceed as element is not empty.');
  }
  else
  {
    alert('Element is empty');
  }
});
Declare a div element "dvText" with no content like this.
<div id="dvText"></div>
See live Demo and Code.
But there is a problem here. If you declare your div like below given code, above jQuery code will not work because your div is no more empty. By default some spaces gets added.
<div id="dvText">
</div>
See live Demo and Code.
So what's the solution? Well, I had posted about "How to remove space from begin and end of string using jQuery", so we will use the trim function to trim the spaces from the begin and end of the html() attribute.
$(document).ready(function() {
  if ($('#dvText').html().trim()) {
    alert('Proceed as element is not empty.');
  }
  else
  {
    alert('Element is empty');
  }
});
See live Demo and Code.
Hope this helps!!!!

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

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..