1

I have a paragraph element which is filled with content used with javascript. And I want to hide that element whenever it has no text within it. I don't want to use the setTimeout nor setInterval; and I don't want to make it a function and call in every function because there's a lot of function that manipulates the content of my paragraph element. What is the best way to do this?

Ryan G
  • 71
  • 1
  • 11
  • 1
    If your `p` has no text, it will not be shown unless you have defined an explicit width/height – Downgoat Apr 08 '15 at 03:46
  • The answer here http://stackoverflow.com/a/16731681/1592716 describes how to do what you're talking about. – Cass Apr 08 '15 at 03:53
  • Yup i have set the width and height of my `p`, that's why I jumped to this scenario if possible. – Ryan G Apr 08 '15 at 06:11

1 Answers1

3

Let's assume that you set some styles on all of your paragraphs, so they are shown even when they are empty, in order to hide them, without changing the javascript codes, you can apply a css style to empty paragraphs using the empty selector as below:

  p:empty { display: none } 

without setting any interval or checking, anytime a p element becomes empty this css rule will hide it from the page.

Check the sample

SOJA
  • 631
  • 5
  • 9
  • 1
    Elegance... I was halfway through writing up something that used https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver when I saw this. – jdphenix Apr 08 '15 at 04:04
  • That's what I'm looking for. Thanks. Another problem will be, how about a divider element has un-ordered list element that when un-ordered list element is empty then the divider element will be hidden. – Ryan G Apr 08 '15 at 06:05
  • 1
    Great, @Aikitchi using the same way, you can hide the 'ul' elements. Use: 'p ul:empty { display:none;} ' if you set a divider style to a 'p' element or 'div ul:empty { display:none;} ' if it is a 'div' and so on... – SOJA Apr 08 '15 at 22:25