1

Have some code to hide a div, if it's contents are empty. This SHOULD work...its' worked before. Am I missing something obvious here? The div class = "msgalert"

$(document).ready(function () {
    if ($('.msgalert').is(':empty')) {
        $(".msgalert").css({'display':'none'});
    }
});

The corresponding CSS is:

.msgalert { border: 1px solid #eac572; background-color: #ffe9ad; }

Please help! Thanks :)

5
  • Does $(".msgalert:empty").css({'display':'none'}); work? Commented May 18, 2012 at 20:17
  • 1
    :empty means absolutely no content, including whitespace, so make sure the elements are actually empty. Commented May 18, 2012 at 20:18
  • 1
    Works fine: jsfiddle.net/jSYC3 Commented May 18, 2012 at 20:18
  • Doesnt work...here is my version! jsfiddle.net/jSYC3/2 Commented May 18, 2012 at 20:59
  • Of course it doesn't work. You included HTML tags in the JavaScript. jsfiddle.net/jSYC3/5 So was the actual issue that you had whitespace inside the element, as I see you do in the demo? Commented May 19, 2012 at 23:04

2 Answers 2

3

Try checking if the length of the html() of .msgalert is 0 instead of checking if it's :empty, like this:

if ($.trim($('.msgalert').html()).length == 0) {

You'll want to trim the html() to account for the whitespace as well.

Sign up to request clarification or add additional context in comments.

15 Comments

I like this instead of :empty selector +1
Why would this provide a different result from :empty?
text() doesn't take into account whitespace, I believe. Making a fiddle to test it now...
It does. Whitespace is text too. ;) You need to $.trim it to see if it's whitespace only.
@ElliotBonneville Yeah, I know it. But 'empty' means 'no content', no tags, no text.
|
1

Just posting my version,

$('.msgalert').filter(function () {
   return ($(this).text().length == 0 && $(this).children().length == 0);
}).css('display', 'none');

3 Comments

included .children check for empty tags :)
@casey7398 Your fiddle was buggy.. try here jsfiddle.net/skram/jSYC3/4 --> btw.. you were trying out Elliot suggestion.
Does it not working have anything to do with <div class=msgalert> being inside of another div id....?

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.