Last Updated: July 27, 2016
· waynedenier

Elegant Empty Lists

It's really easy to get off the rails injecting "empty" messages in to lists of HTML elements when the contents of a list change. If you aren't hitched to a heavy 2-way databinding framework (such as Angular) then there's a really simple way to handle this using just HTML and CSS pseudo-selectors that can cut out some otherwise brittle JavaScript.

tl;dr http://jsfiddle.net/qsj4m/

  • Create a list element to contain your items. This can be an <ul>, <table> or whatever you like. Inside the list, add a static item for your empty message. Label the item with a unique class selector that you can use later.
<ul id="some-list">
   <li class="empty-message">There are no items at this time.</li>
  • Declare a css class that hides it by default, and another that only shows it if it's the last child element in the list.
.empty-message {
  display: none;

.empty-message:last-child {
  display: block;
  color: #999;
  • Now if you want to fill the list using jQuery, you can just $('#some-list').append(blah) new records. The empty list message disappears once new items are entered!

  • If you need to clear the list, you can exclude the empty-message with a selector, such as $('#some-list li:not(.empty-message)').remove().

As mentioned earlier, you might find another way to hide this message if you're using a 2-way databinding framework. Angular would let you ng-show the empty message only when the $scope model object it's bound to have a .length = 0 and so on. However if you're just using jQuery or even vanilla JavaScript, this CSS trick could save you some code.