jQuery: Remove parent element containing empty span
This tutorial explains how to remove the parent of an element that contains an empty <span>
(or any empty element). First I’ll explain where it might be useful, and then share the magical code to make it happen.
Why is it useful?
This technique is useful in any scenario where you want to remove not just an empty span or div, but also the parent element. For example if you have this markup, it may be useful to remove it:
<p>
<span></span>
</p>
This happens frequently with WordPress. Any post that includes the more tag will output the above markup on the frontend. For WordPress, the actual empty HTML output looks like this:
<p>
<span id="more-1"></span>
</p>
In many cases this is not a problem, but depending on your theme, styles, and other factors, it may be necessary to remove the empty span and parent element (paragraph in this example).
How to remove it
There are several ways to remove the empty span and paragraph. Or it could be any two empty elements. Here is the jQuery/JavaScript code to do it:
$('span:empty:only-child').parent('p').remove();
No edits need made, simply add the code and done.
What it’s doing? First it selects empty <span>
elements that are an only child of the <p>
element. Then it removes both span and paragraph tag. To use this technique for other tags, simply replace span
and p
with the child and parent elements that you want to remove when empty.
Note that this technique removes only the first matching empty tags (like the WordPress example). To target and remove multiple empty elements, check out the next section.
Remove multiple empty elements
The above code technique works only for the first matching set of empty elements. To remove multiple empty elements, use this code instead:
$('p').each(function() {
var $this = $(this);
if ($this.html().replace(/\s| /g, '').length == 0) {
$this.remove();
}
});
No edits are required, just add to your JavaScript and done. When added, this code loops through all paragraph tags and removes them if empty OR include only blank/empty spaces.
More tips & tricks
Here is a simpler jQuery technique to remove all empty elements:
$('*:empty').remove();
But I did not have 100% success when testing this method. It’s simpler, but may not be suitable in all cases.
No JavaScript? It’s also possible to do this trick with pure CSS, as explained in my tutorial over at DigWP.com.