6

I have the following HTML :

<div id="rightCon">




                    </div>

And then I have the following script at the top :

$('#rightCon:empty').hide();

Why is the div not hiding? I can see that there is some spaces(that I can´t get ridoff) but does that really matter? How do I remove/hide this div when its empty with only spaces?

Lucio
  • 4,753
  • 3
  • 48
  • 77
Banshee
  • 15,376
  • 38
  • 128
  • 219
  • Possible duplicate of [Hiding an element that contains only spaces using CSS](https://stackoverflow.com/questions/13380906/hiding-an-element-that-contains-only-spaces-using-css) – Eugen Konkov Apr 11 '18 at 09:59

3 Answers3

7

Your element appears to have a bunch of white space, which will give it a text node. It won't be matched by :empty for that reason.

You could try finding the element and checking it's contents explicitly:

$('#rightCon').filter(function() {
  var text = $(this).text().replace(/\s*/g, '');
  return !text;
}).hide();
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • It will only hide the element if the `.filter()` function thinks that the element contains nothing but white space. – Pointy Sep 06 '13 at 23:49
  • @SnowJim oops sorry; the regex needs a "g" - updating answer – Pointy Sep 06 '13 at 23:59
  • @Lucio yes I just figured that out :) Thanks!! – Pointy Sep 07 '13 at 00:02
  • @SnowJim You should mark this answer as *accepted*. [It is working](http://jsfiddle.net/aQ4qH/) – Lucio Sep 07 '13 at 00:06
  • @Pointy, the original answer was only incorrect in that it had `!!` in the return statement instead of `!`. The `g` in the regex is not necessary. I assume there is no special jQuery selector to match an element which has only whitespace content in text nodes. – Jake Jan 19 '23 at 02:12
  • @Jake not as a selector. Excluding such effectively empty elements is what the code above does. – Pointy Jan 19 '23 at 02:16
4

This solved the problem.

$(document).ready(function () {
                if($('#rightCon').text().trim().length < 1)
                {$('#rightCon').hide();}
            });
Banshee
  • 15,376
  • 38
  • 128
  • 219
0

Your div is not actually empty (It contains whitespace). So the selector $("#rightCon:empty") will never evaluate and hide the div.

Since HTML elements should be unique, you can safely assume that you can select the correct element via:

var rightCon = $("#rightCon");

You can then hide the element via:

right.hide();

Or

 $("#rightCon").hide();
Darren
  • 68,902
  • 24
  • 138
  • 144