Check which p has no text

Asked

Viewed 324 times

1

How to verify 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 tag p have no text, add display: none; in the same.

  • Guy but a <p></p> is already "display:None" by nature. The empty P tag does not take up space on the page...

3 answers

5


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');
  }
});

2

If you don’t want to use jQuery, you can do so:

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');
  • Your JS will not work if the <p> and the closure </p> are on different lines. A line break in the code generates character, so the tag will not be empty.

  • Solution: add one .trim(): if (! el.textContent.trim()) {

  • @perfect sam, thank you.

1

This would be the code snippet in Jquery:

$('p:empty').css('display', 'none');
  • 1

    $('p:empty').hide(); has the same effect and I find even more elegant :)

  • True, another option that answers the question and still writes less code :P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.