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?
Related Topics
jQuery: Show or hide DIV-Container depending on Checkbox State
Tutorial | 0 Comments
jQuery: Show a DIV - Hide other DIVs
Tutorial | 0 Comments
JavaScript: Show and hide HTML area by clicking a link
Tutorial | 0 Comments
jQuery: Load and Replace DIV Content with clicking Links
Tutorial | 0 Comments
jQuery: Make Full DIV Container Clickable
Question | 3 Answers
HTML5 Validator: How to fix "Warning trimming empty <p> or <div>"
Question | 1 Answer
jQuery: Read and Change Data Attribute Value
Tutorial | 0 Comments
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.
For example, you can achieve this in the way, it is shown in the following example:
Or you can use this way:
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?
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:
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