Without using jQuery, in pure JavaScript, the querySelectorAll
method accepts the :empty
:
document.querySelectorAll('p:empty');
In this way you will restrict the loop to only <p>
empty elements, instead of going through ALL <p>
, bypassing verification with if
:
const els = document.querySelectorAll('p:empty');
els.forEach(x=>{ x.style.display = "none" });
Only a problem exists that can occur: If the <p>
tag only has whitespace (spaces are also characters) the querySelectorAll('p:empty')
will 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 :empty
selector of jQuery works differently and will consider both examples above "empty"; already the% of querySelectorAll
only the 1st.
In case of using jQuery, just use the :empty
selector with .hide()
:
$('p:empty').hide();
If there is a possibility mentioned above, of <p>
is closed in another line, using pure JavaScript, Luiz Filipe's answer is satisfactory using if
, however it is necessary to add the .trim()
function to clear the characters empty:
const els = document.querySelectorAll('p');
els.forEach(el => {
if (!el.textContent.trim()) {
el.style.setProperty('display', 'none');
}
});