Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .remove not working for nested element

Tags:

jquery

I'm trying to simply remove all nested li elements within ul, but it is not working. Why won't this snippet work? What am I missing?

html

<ul id="myul">
</ul>
<br/>
<button onclick="add();">add</button><br/>
<button onclick="remAll();">remove all</button>

js

function add()
{
    $('#myul').append('<li>hello world</li>');
}

function remAll()
{
    $('#myul').remove('li');
}

http://jsfiddle.net/gPnxY/

like image 405
Nick Rolando Avatar asked Jan 19 '26 21:01

Nick Rolando


2 Answers

Do this instead, the selector argument for remove() is a filter for the object in question. In this case the object in question is just the single element with the id myUl, therefore not containing any <li> elements.

jsFiddle

$('#myul').find('li').remove();

or

$('#myul li').remove();
like image 156
Gabe Avatar answered Jan 22 '26 14:01

Gabe


jsFiddle here

This is nice:

$('#myul').empty();

Read more cool stuff: http://api.jquery.com/empty/

Also:

$('#myul').find('li').remove();
$('#myul li').remove();
$('#myul').contents().remove();
$('#myul').html('');
like image 20
Roko C. Buljan Avatar answered Jan 22 '26 14:01

Roko C. Buljan