Without using jQuery, in pure Javascript, the method querySelectorAll
accepts the selector :empty
:
document.querySelectorAll('p:empty');
This way will restrict the link only to the elements <p>
empty, instead of running through ALL <p>
, dispensing with verification with if
:
const els = document.querySelectorAll('p:empty');
els.forEach(x=>{ x.style.display = "none" });
Only that there is a problem that can occur: case the tag <p>
possess only blanks (spaces are also characters) the selector querySelectorAll('p:empty')
will not select. Examples:
1º. <p></p> -> esta tag está vazia
2º. <p> -> esta tag NÃO está vazia,
</p> possui espaços porque está sendo fechada em uma nova linha
The selector :empty
jQuery works differently and will consider both of the above "empty" examples; whereas the querySelectorAll
only the first.
In case you use jQuery, just use the selector :empty
with .hide()
:
$('p:empty').hide();
If the above possibility exists, <p>
be closed in another line, using pure Javascript, Luiz Filipe’s answer is satisfactory using the if
, but it is necessary to add the function .trim()
to clear the empty characters:
const els = document.querySelectorAll('p');
els.forEach(el => {
if (!el.textContent.trim()) {
el.style.setProperty('display', 'none');
}
});
Guy but a
<p></p>
is already "display:None" by nature. The empty P tag does not take up space on the page...– hugocsl