top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How do you check if an element is empty?

+2 votes
420 views
How do you check if an element is empty?
posted Jul 8, 2015 by Shivaranjini

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

check or verify that the element that you are accessing in jQuery 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>

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>

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');
  }
});
answer Jul 9, 2015 by Karthick.c
...