Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an HTML element is empty using jQuery?

I'm trying to call a function only if an HTML element is empty, using jQuery.

Something like this:

if (isEmpty($('#element'))) {     // do something } 
like image 407
vitto Avatar asked Jul 25 '11 08:07

vitto


People also ask

How check HTML element is empty 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.

Is (': Empty ') in jQuery?

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.

How do I check if a div is empty in HTML?

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.


1 Answers

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.

like image 100
Emil Avatar answered Sep 22 '22 15:09

Emil