jQuery: dealing with empty elements

From a DOM perspective, an element is said to be empty when it doesn't contain child nodes. In other words, an element is empty when its firstChild property is set to null. Consider the following markup:

<p id="test1"></p>
<p id="test2">  </p>

In this case, only the first paragraph is empty, because the second one contains some white-space that is considered as a text node. In jQuery we can only check whether an element contains other elements, for example by using the html() method or the length property, but in either case we have to know in advance what kind of element we're actually searching for. So we can write the following plugin in order to address the particular case showed earlier:

(function($) {


   $.fn.isEmpty = function() {
   
   
       if(this[0].firstChild == null) {
       
           return true;
       
       
       } else {
       
       
           return false;
       
       }
   
   };



})(jQuery);

This plugin checks only if the firstChild property of a given element is null or not. Once applied to our example, it returns the following results:

$(document).ready(function() {

  alert($('#test1').isEmpty()); // true
  alert($('#test2').isEmpty()); // false



});

As you can see, this turns out to be very useful when we're traversing the DOM in a while loop or when we want to get a map of our DOM tree.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: dealing with empty elements”

Leave a Reply

Note: Only a member of this blog may post a comment.