开发者

jQuery loop ul li

开发者 https://www.devze.com 2023-01-12 13:58 出处:网络
What\'s wrong with this? I\'m trying to hide all empty li. $(document开发者_StackOverflow中文版).ready(function() {

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

    $(document开发者_StackOverflow中文版).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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消