How to Select Empty Elements with jQuery :empty
The jQuery :empty selector provides a fast and efficient
way to target DOM elements that have no child nodes, including text
nodes. This article explains how the :empty selector
functions, provides practical code examples for selecting and
manipulating empty elements, and highlights common pitfalls such as
hidden whitespace and self-closing tags.
What is the :empty
Selector?
In jQuery, the :empty selector matches any element that
does not contain child elements or text. If an element contains another
tag, plain text, or even a single space, jQuery does not consider it
empty.
Basic Syntax
To select every empty element on a page:
$(':empty')To restrict the selection to a specific tag type, prepend the tag name:
$('p:empty')
$('div:empty')
$('td:empty')Practical Examples
1. Highlighting or Hiding Empty Elements
You can select empty elements and apply styles or hide them dynamically:
// Hide all empty paragraph elements
$('p:empty').hide();
// Add a placeholder class to empty table cells
$('td:empty').addClass('no-data');2. Inserting Default Content
You can target empty containers and populate them with fallback text:
// Add placeholder text to empty summary divs
$('div.summary:empty').text('No summary provided.');3. Removing Empty Nodes from the DOM
To clean up markup by stripping out empty tags:
// Remove all empty list items
$('li:empty').remove();Important Considerations
- Whitespace Counts as Content: An element like
<div> </div>contains a text node (the space) and will not be matched by:empty. If your markup may contain whitespace, strip the whitespace first or use a custom filter:$('div').filter(function() { return $.trim($(this).text()) === '' && $(this).children().length === 0; }); - Self-Closing and Void Tags: Elements such as
<input>,<img>, and<br>have no child elements by definition. A broad$(':empty')query will match these elements. Always qualify the selector with a tag name (such as$('div:empty')) to avoid unintended selections.