Reputation: 3066
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
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
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
Reputation: 100175
$('ul li:empty').remove();
//OR
$('ul li').filter(function() {return $(this).text() == '';}).remove();
Upvotes: 1
Reputation: 41757
Try the following:
$('li').filter(function() { return !$(this).html(); }).remove();
Upvotes: 1
Reputation: 35793
Should be able to use the empty selector:
$('li:empty').remove();
http://jsfiddle.net/infernalbadger/4yf2t/
Upvotes: 2
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
Reputation: 4557
With just a jQuery selector
$("ul li:empty").remove();
Upvotes: 8
Reputation: 1853
$('li').each(
function(){
if($(this).html().trim()==''){$(this).remove();}
}
);
Upvotes: 1