0
(0)

I want to show you a small trick for an annoying problem. There are situations when you have paragraphs in the document that don’t have tags or text inside only space. Because of that the paragraph having some padding applied to it, it will still take up space in the documents layout.

In the CSS we have border and padding applied to every paragraph:

 p {
  border: 1px solid;
  padding: 10px;
}

The idea is to remove all paragraphs that don’t have any text or HTML tag inside. CSS would be my first tool, to accomplish this:

p:empty {
  display: none
}

The :empty pseudo selector only hides the tags that don’t have elements, text or white-space inside. In our case one paragraph has white-space inside without anything else but we don’t have any selector or method to remove that space or to mark it as empty.

There was an implementation for targeting white-space-only elements and that was the :blank selector but it was removed and the :empty should do this in the feature but for now it does not work that way.

So let’s do it then with Javascript. We can search for paragraphs in the document and filter out the ones that are empty or have only space content:

document.querySelectorAll('p').forEach(tag => {
   if(!tag.innerText.trim().length) tag.remove();
});

In the code above we just checked if after removing space in each case of a paragraph’s text content, there isn’t any content left, then it means that it is empty and should be deleted.

As I promised this will be a short article. Thank you for your attention !

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in: