Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the content of a DIV is empty in jQuery

Tags:

html

jquery

size

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>
...
like image 355
RayLoveless Avatar asked Jun 21 '11 02:06

RayLoveless


People also ask

How check div content is empty or not in jQuery?

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.

How do I check if a div element is empty?

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.

Is (': Empty ') in jQuery?

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.

How do I check if a div has content?

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.


1 Answers

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() ) );
like image 124
user113716 Avatar answered Oct 03 '22 15:10

user113716