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 badges8 Answers
Reset to default 8With 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();