tags:

views:

52

answers:

3
+1  Q: 

jQuery loop ul li

What's wrong with this? I'm trying to hide all empty li.

    $(document).ready(function() {
        $("#details li").each(function() {
            if ($(this).length == 0) {
                $(this).css({ display: "none" }); ;
            }
        });
    });

Markup:

<ul id="details">
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <li></li>
 <li></li>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
</ul>

Thank you in advance

A: 

The expression $(this).length cannot possibly be zero.

Pointy
+4  A: 

I think what you want is the .text() length, like this:

$(function() {
  $("#details li").each(function() {
    if ($(this).text().length == 0) {
      $(this).css({ display: "none" }); ;
    }
  });
});

Or a bit shorter:

$("#details li").filter(function() {
  return $(this).text().length == 0;
}).hide();

Or a slightly different check that works for your purposes, courtesy of @Rafael:

$("#details li:empty").hide();
Nick Craver
You should always `$.trim()` before checking length (due to whitespace in HTML).
Marko Dumic
@Marko - If there might be white-space yes do this...if you're *assured* there's not (can't tell from the example), same the regex calls :)
Nick Craver
You can just do $('#details li:empty').hide();
Rafael
@Nick Craver, You sir are the man!
Muad'Dib
@Rafael - `:empty` is a slightly different check, though it would work for the author's purpose, you're right.
Nick Craver
@Marko You're the man as well!
Muad'Dib
@Rafael, Thank you as well
Muad'Dib
+4  A: 

Try using:

if ($(this).is(':empty')) {}

Furthermore, you should be able to re-write the above code as:

$("#details li:empty").each(function() {
  $(this).css({ display: "none" });
});

Or even:

$("#details li:empty").hide();
Kevin Sylvestre