Explain Codes LogoExplain Codes Logo

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

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Jan 28, 2025
TLDR

Here's a lightning-fast way to check if an element on your page is empty:

$('#elementId').is(':empty') // returns true if empty, false otherwise

This works by using the :empty selector which targets elements that have no children or text nodes. However, this is not the only way to accomplish this task, and we'll delve deeper into this fascinating topic!

Dealing with whitespace

Spaces can be knotty! They might appear to be nothing, but for our :empty selector, they hold weight. To tackle this nuance, we trim it down before checking:

// "I ain't afraid of no space!" - Ghostbusters, probably $.trim($('#elementId').html()) === '' // returns true if visually empty

Bringing child nodes into play

The HTML family can be vast, with countless child elements and text nodes under a single parent. To include these "unseen" elements, we use hasChildNodes:

// Asking politely: "Kids, are you in here?" !$('#elementId')[0].hasChildNodes() // returns true if no child elements or text nodes

What about just the child elements?

Ignore the text nodes, what if you just want to know about the child elements?

// Looking out for the little ones $('#elementId').children().length === 0 // returns true if no child elements

This method scans for just the child elements, disregarding any text nodes present.

Making it reusable with jQuery.fn

Looking for a way to extend jQuery's capabilities, saving a few keystrokes, and wrapping the logic in a more readable package? Enter jQuery.fn:

jQuery.fn.isEmpty = function() { // Helping us stay DRY. Reducing code redundancy, one function at a time return !$.trim(this.html()); }; // To use the function: if ($('#elementId').isEmpty()) { // Perform action if empty }

This approach keeps your code tidy, allows for seamless integration into larger jQuery chains, and looks snappy to boot!

Conditional execution

Let's keep it sleek. Execute functions only when an element is stark empty:

// "You shall not pass!" - Gandalf, if he were a function $('#elementId').is(':empty') && someFunction(); // someFunction executes if element is empty

This makes your code easy on the eyes, and emphasises the dependence of the function execution on the state of the element.

Steering clear of :empty deceptions

The :empty selector counts spaces and line breaks as content:

// Empty or not? That is the question $('div:empty').length; // May return 0 for div, even if there's whitespace or line breaks

Remember to handle this, maybe with trim, before you use the :empty check.

Dealing with dynamically loaded content

In a world where content loads or changes in real-time, our static emptiness check might struggle. Fear not, here's how to tackle it:

// Waiting for our friends, the dynamic content, to arrive loadContent().then(() => { if ($('#elementId').is(':empty')) { // Take action if the element's looted empty } });

Also, the savvy event-driven scenario:

// Because input changes matter $('input').on('change', function() { if (!$(this).val()) { // Input field is as blank as my mind on a Monday } });

Emphasizing visually empty elements

A truly visually empty element is unfilled by anything visible to users, regardless of any invisible party crashers like hidden inputs or scripts. Here's how we can craft this check:

function isVisuallyEmpty(element) { // "I see no content!" - Sherlock Holmes, inspecting our element return !$(element).children().not(':hidden').length && !$.trim($(element).text()); } if (isVisuallyEmpty('#elementId')) { // The element's emptier than my wallet after payday }

This function checks for both visible child elements and the existence of non-whitespace text.