jQuery

jQuery Check If Div Is Empty Examples

When working with Divs and jQuery, there might have been a situation when you needed to know dynamically if any given div contains any content at all or not. Based upon this, you might want to trigger an action. So in this article, I am going to share easy ways to find out if a Div is empty or not by means of easy to follow examples. Check out the Demo to see how it works in real time.

How To Check If Div Is Empty Using jQuery

Let’s assume that we have three  divs with IDs ‘my_div1’, ‘my_div2’ and ‘my_div3’.

‘my_div1’ will not contain any content,  ‘my_div2’ will have content in it and  ‘my_div3’ will contain only a single space and no actual content. Now we will check if there are any contents in these div or not using jQuery

Here is the common HTML for all the following examples:

Example 1:  Check if div is empty and alert the status when a button is clicked

Results of Example 1:

When you run the above code and click on the first button, you will see an alert that says that my_div1 is Empty. This is correct as there is no content in it.

When you click on the second button, you will see an alert that says that my_div2 is Not Empty. This is correct as there is some custom content in it.

When you click on the third button, you will see an alert that says that my_div3 is NOT Empty. Well, as far as we can see, there is no content in it. Yet, the alert says that my_div3 is NOT empty. Why? Are you surprised why? Well, here’s the reason. ‘my_div3’ does not contain any actual text or any other HTML content BUT it does contain a “space” or “white space”. Now even a space is considered as the content of a div. And for this reason, we see the alert that it is NOT empty. So how to fix this? Our next example will solve this situation.

Example 2:  Apply trim to a div’s content and then check if it is empty or not

In the above code, we first retrieve the HTML content of the “my_div3” . This will remove any spaces in the retrieved content. Now we check this to see if it is empty or not. This will give us the correct output.

Your Turn!

Do you know of any other ways to check if a div is empty or not using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*