Recently a client asked for a simple way to remove empty HTML tags in their content. The HTML in question had a number of H2 tags that had no content but were creating space in their WordPress posts. Naturally you could simply remove them using the editor, but in this case the client had imported thousands of posts and didn’t have time to go through and edit them. Fortunately there are two easy solutions to hand.

The first was a Javascript/JQuery snippet as follows (the parent container had the CSS class .post-content):

$('.post-content h2').each(function(){

The second solution is far simpler. CSS now has the ability to filter out such elements, so by adding the following code to your stylesheet, no empty H2 tags will be displayed in the parent container, or in this case, anywhere else on the site for that matter:

h2:empty { display:none; }

So there you have it. Two solutions, one jQuery, one CSS, though it’s clear to see which is the smart one to use.