Search code examples
htmlcsshidepseudo-class

Hiding an element that contains only spaces using CSS


I am trying to hide the following element in an automatically generated HTML document:

  <p id="sitspagedesc" class="sitspagedesc">

    </p>

In some pages, the <p> tag will contain an inner value but in others it can contain only spaces as shown in the example. I need to find a way of hiding this so that it is hidden using CSS only, as changing the HTML is not an option.

I have tried to hide it using

.sitspagedesc:empty
{
display:none;
}

but this does not work, presumably on the account of the spaces the element contains.

Does anyone have any good ideas?

Thanks :)


Solution

  • I don't think you can do it with pure CSS.

    However with a little JavaScript you can do it.

    var allParas = document.getElementsByTagName('p');
    //filter by class name if desired...
    for(var i=0;i<allParas.length;i++){
      if(allParas[i].getElementsByTagName('*').length == 0){
        allParas[i].style.display = 'none';
      }
    }
    

    If you have access to jQuery it is a little easier to do the filtering with their built in selectors.

    $('p.sitspagedesc').each(function(){
      if($(this).children().length == 0){
        $(this).hide();
      }
    });