0

Possible Duplicate:
Remove Empty elements with jQuery

I want to remove empty <li> using jQuery. I am trying to do this but my code is not working as per my requirements. My code is show below.

Script

$(document).ready(function(e) {
    $('#u li').each(function() {
        if($(this).html(' ')) {
            $(this).remove();
        }
    });
});

HTML

<ul id="u">
    <li>hi</li>
    <li></li>
</ul>
2
  • @swapnesh The id of the element is u, hence #u... #ul wouldn't match anything (you're thinking of ul, but that would match every ul element instead of that particular one). Commented Jul 20, 2012 at 12:59
  • @Juhana lol my bad really :( i missed that stuff :( Commented Jul 20, 2012 at 13:01

3 Answers 3

5

It should be as simple as that:

$('#u li:empty').remove()
Sign up to request clarification or add additional context in comments.

1 Comment

Note: This does not match elements that have a space, non-breaking space or other non-visible characters, because those <li> elements do have a child text node. See jsfiddle.net/zeYMN
5

You are setting the html of the <li> to one space character, not checking if it's empty. Instead, try this (trimming might be a good idea to catch spaces and newlines):

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

Also, you could use jQuery's :empty selector (this checks all child nodes including text nodes):

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

However, this does not match elements with "invisible text nodes", for example <li> </li> (one space) → jsfiddle.

Comments

1
<script>
    $(document).ready(function(e) {
        $('#u li').each(function() {
            if($(this).html().length == 0)
            {
                $(this).remove();
            }
        });
    });
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.