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?

1

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

6 Comments

It will only hide the element if the .filter() function thinks that the element contains nothing but white space.
@SnowJim oops sorry; the regex needs a "g" - updating answer
@Lucio yes I just figured that out :) Thanks!!
@SnowJim You should mark this answer as accepted. It is working
@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.
|
4

This solved the problem.

$(document).ready(function () {
                if($('#rightCon').text().trim().length < 1)
                {$('#rightCon').hide();}
            });

Comments

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();

5 Comments

Yes, but that means it will always be hidden, I need it to only be hidden when it got whitespaces.
That will hide the element whether it has stuff in it or not.
You should use Regular Expressions.
Damn didnt know the pseudo selector existed
@SnowJim - you can use a regular expression or use val to see if the div contains any content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.