Check which p has no text

1

How can I check which p has no text value?

I have the following HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p>aaaaaaaaaa</p>
    <p>bbbbbbbbbb</p>
    <p></p>
    <p>aaaaaac</p>
    <p></p>
    <p>uuuuuuuuuuu</p>
</body>
</html>

If the p tag does not have text, add display: none; to it.

    
asked by anonymous 05.09.2018 / 00:22

3 answers

5

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');
  }
});
    
05.09.2018 / 01:42
2

If you do not want to use jQuery, you can do this:

const els = document.querySelectorAll('p');

els.forEach(el => {
  if (! el.textContent) {
    el.style.setProperty('display', 'none');
  }
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p>aaaaaaaaaa</p>
    <p>bbbbbbbbbb</p>
    <p></p>
    <p>aaaaaac</p>
    <p></p>
    <p>uuuuuuuuuuu</p>
</body>
</html>

With jQuery:

$('p:empty').css('display', 'none');
    
05.09.2018 / 00:27
1

It would look like the code snippet in JQuery:

$('p:empty').css('display', 'none');
    
05.09.2018 / 00:26