最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to remove empty li in ul list using jquery? - Stack Overflow

programmeradmin10浏览0评论

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?

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?

Share Improve this question edited Sep 29, 2012 at 10:27 Eli 14.8k5 gold badges61 silver badges77 bronze badges asked Jan 9, 2012 at 10:05 Ravichandran JothiRavichandran Jothi 3,06611 gold badges54 silver badges83 bronze badges
Add a ment  | 

8 Answers 8

Reset to default 8

With just a jQuery selector

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

http://jsfiddle/acS9A/

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

I would suggest you to trim the html before the parision, 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")

Should be able to use the empty selector:

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

http://jsfiddle/infernalbadger/4yf2t/

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

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

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

Try the following:

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

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


发布评论

评论列表(0)

  1. 暂无评论