Ravichandran Jothi
Ravichandran Jothi

Reputation: 3066

How to remove empty li in ul list using jquery?

I have the below HTML structure:

<ul>
    <li><a>one</a></li>
    <li><a>two</a></li>
    <li></li>
    <li><a>three</a></li>
    <li><a>four</a></li>
    <li></li>
    <li><a>five</a></li>
</ul>

I need to remove the li elements which are don't have any content (<li></li>).

How can I do this in jQuery?

Upvotes: 2

Views: 9035

Answers (8)

Iakov Mishchenko
Iakov Mishchenko

Reputation: 116

$('li').each(function(){
if($(this).html() == "" || typeof($(this).html())=="undefined")
{
    $(this).remove
}
})

I would suggest you to trim the html before the comparision, so that you do not end up counting:

<li>
</li>

as a non empty item. To trim the html, simply add .trim() after .html() i.e:

if($(this).html().trim() == "" || typeof($(this).html().trim())=="undefined")

Upvotes: 3

PeeHaa
PeeHaa

Reputation: 72652

Untested so let me know if it doesn't work for you.

$('li').each(function() {
    var li = $(this);
    if (li.html() == '') {
      li.remove();
    }
});

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175


$('ul li:empty').remove();
//OR
$('ul li').filter(function() {return $(this).text()​​​​​​​ == '';}).remove();​


Upvotes: 1

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

Try the following:

$('li').filter(function() { return !$(this).html(); }).remove();

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

Should be able to use the empty selector:

$('li:empty').remove();

http://jsfiddle.net/infernalbadger/4yf2t/

Upvotes: 2

Guffa
Guffa

Reputation: 700192

You can use the filter method to run a custom function to find the elements to remove:

$('ul li').filter(function(){ return $(this).text() == '' }).remove();

Upvotes: 1

Christopher Manning
Christopher Manning

Reputation: 4557

With just a jQuery selector

$("ul li:empty").remove();

http://jsfiddle.net/acS9A/

Upvotes: 8

Ahmad Hajjar
Ahmad Hajjar

Reputation: 1853

  $('li').each(
         function(){
             if($(this).html().trim()==''){$(this).remove();}
         }
  );

Upvotes: 1

Related Questions