I'm trying to call a function only if an HTML element is empty, using jQuery.
Something like this:
if (isEmpty($('#element'))) { // do something }
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.
The 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. Tip: To remove the elements and its data and events, use the remove() method.
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.
if ($('#element').is(':empty')){ //do something }
for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/
EDIT:
As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).
function isEmpty( el ){ return !$.trim(el.html()) } if (isEmpty($('#element'))) { // do something }
You can also make it into a jQuery plugin, but you get the idea.
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