Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 700
Andy Kaufman Avatar asked Sep 07 '25 07:09

Andy Kaufman


2 Answers

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();
  }
});
like image 67
scunliffe Avatar answered Sep 09 '25 19:09

scunliffe


If the desire is to mimic the functionality of the :empty selector except that whitespace is ignored, the accepted answer (by scunliffe) doesn't quite work. It only checks for child elements, and this doesn't account for text directly inside the selected element. For instance, <p>Hello World!</p> would be treated as empty because it has no child elements even though it does contain non-whitespace text.

My solution uses the jQuery.trim() function to remove leading and trailing whitespace from the .text() value which contains the combined text contents of the selected element and its descendants. So the selected element is hidden if it contains no non-whitespace text and no child elements. As with the :empty selector, HTML comments are not counted as content since they are not reflected in either the .text() or .children() values.

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

See the Fiddle at https://jsfiddle.net/TNTitan89/crejkbxq/.

like image 33
Garland Pope Avatar answered Sep 09 '25 18:09

Garland Pope