04 Votes

jQuery: Check whether a DIV container is empty

Question by PC Control | 2012-09-15 at 17:55

I want to evaluate using jQuery, if a DIV container is empty, for instance, this container here:

<div id="mydiv"></div>

Is there a specific test function of jQuery, which can be used for this purpose?

ReplyPositiveNegative
5Best Answer7 Votes

For example, you can achieve this in the way, it is shown in the following example:

if ($('#mydiv').html()) {
   alert('The container contains something.');
} else {
   alert('The container is empty.');
}

Or you can use this way:

if ($('#mydiv').is(':empty')) {
   alert('The container is empty.');
} else {
   alert('The container contains something.');
}

In the first example, we retrieve the contents of the element with .html(). The if-condition is true, if there is any content in the container and it is false, if the result of .html() is empty.

In the second example, we use the jQuery selector :empty and we test, whether the element in question belongs to the empty elements (is(':empty')).

Whitespace in the DIV

What happens in the case, when there is only white space such as spaces, tabs and line breaks in the DIV?

<div id="mydiv"> </div>

The two functions above would say that the DIV is containing a content. If we do not want this for whitespace, we can use the following trick:

if ($('#meindiv').html().trim()) {
   alert('The container contains something.');
} else {
   alert('The container is empty.');
}

With trim(), we ensure that the white space will be removed before and after the "real" content. What remains is an empty string in the event that the container previously contained only whitespace, and so, the result of the if-condition will be false. Only if there is really any text contained in the element, the condition will be true.
2012-09-15 at 18:43

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.