How do I use jQuery to check to see if the content of a <div>
is empty?
I tried this and is doesn't seem to be printing the correct values.
...
var unframed_items = $("#unframed-items");
alert(unframed_items.html().length);
...
<div id="unframed-items"> </div>
...
Method 1: Using the “:empty” selector: The element to be checked using is() method. The is() method is used to check if one of the selected elements matches to the selector element. This method can be used on this element to test if it is empty by using “:empty” selector.
Use the childNodes property to check if a div element is empty. The childNodes property returns a NodeList of the element's child nodes, including elements, text nodes and comments. If the property returns a value of 0 , then the div is empty.
jQuery empty() MethodThe empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method.
To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
If you mean really empty, use the empty-selector
[docs] :
alert( !!$("#unframed-items:empty").length )
or
alert( $("#unframed-items").is(':empty') )
If you consider whitespace-only to be empty, then use the jQuery.trim()
[docs] method:
alert( !$.trim( $("#unframed-items").html() ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With