Hide empty <li>
Asked Answered
V

2

7

I want to hide all the <li> if they are empty or if there any blank space in <li>.

I am doing it like this:

$("li:empty").filter(function(i,v){return $.trim($(v).text()).length == 0;}).css('display', 'none');

Is this the wrong syntax?

If I create a class to make empty <li> invisible, it works fine. Like this:

$("li[class='hideLi']").filter(function(i,v){return $.trim($(v).text()).length == 0;}).css('display', 'none');

But I don't know which <li> will be empty .

Can anybody help me plz. I want to do display=none if the <li> is empty.

Here is my code:-

<script src="http://code.jquery.com/jquery-latest.js"></script>




<script>
  $(document).ready(function(){
    $("td:empty").css('display', 'none');
     $("div:empty").css('display', 'none');
     $(!$.trim('li:empty')).hide();
     $("li[class='hideLi']").filter(function(i,v){return $.trim($(v).text()).length == 0;}).css('display', 'none');
  });
  </script>

<ul>
  <li style="border:red solid 1px ">HI</li>
  <li style="border:green solid 1px ">  </li>
    <li style="border:blue solid 1px " class="hideLi">  </li>
  </ul>

Thanks,

Vittorio answered 26/3, 2013 at 16:45 Comment(1)
The :empty selector will pick up only those nodes that have nothing -- not even a space -- in them. That's the problem. $('li:empty') has filtered out those li nodes with space in it. So the later filter is useless. Try @Vassilis 's answer.Anzio
B
6
$('li').filter(function(){
    return $.trim($(this).html()) == '';
}).hide()
Bregma answered 26/3, 2013 at 16:56 Comment(1)
What if I have this: <li><a></a></li>. If the anchor text is empty, hide the LI. Update: Resolved it. Thanks! +1Valid
F
9

You can use .hide()

To make this work if you have spaces, you can use jQuery.trim()

$("li").each(function() {

    if(!$.trim($(this).html())) {
        $(this).hide();
    }
});

working example: fiddle example

Freemon answered 26/3, 2013 at 16:47 Comment(2)
$(!$.trim("li:empty")).hide() is equivalent to $(!"li:empty").hide() ==> $(false).hide(), so what's the point?Anzio
I have updated my answer and added a working fiddle using <li>Freemon
B
6
$('li').filter(function(){
    return $.trim($(this).html()) == '';
}).hide()
Bregma answered 26/3, 2013 at 16:56 Comment(1)
What if I have this: <li><a></a></li>. If the anchor text is empty, hide the LI. Update: Resolved it. Thanks! +1Valid

© 2022 - 2024 — McMap. All rights reserved.