Hiding an element that contains only spaces using CSS

前端 未结 9 565
不思量自难忘°
不思量自难忘° 2021-01-07 17:34

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

  

9条回答
  •  忘掉有多难
    2021-01-07 17:48

    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,

    Hello World!

    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/.

提交回复
热议问题