Reputation:
I want to remove all li
except first child
This code is removing all li
..
function clearAll() {
var sidemenu = document.getElementById('side_menu');
while (sidemenu.childNodes.length > 1) {
sidemenu.removeChild(sidemenu.lastChild);
}
}
Any suggestion?
Upvotes: 2
Views: 4637
Reputation: 41
Use Element.replaceChildren()
.
sidemenu.replaceChildren(sidemenu.firstElementChild);
Upvotes: 2
Reputation: 15481
Try doing:
while (sidemenu.childNodes.length > 2) {
//...
}
(Change the condition in the while loop.)
sidemenu.childNodes
actually has one extra text field. For that reason we need to increment the number in the condition of while loop.
jsFiddle Demo (checkout the console)
That ways, all of your <li>
's except the first one will be removed.
Upvotes: 0
Reputation: 1207
use sidemenu.children
instead of sidemenu.childNodes
sidemenu.children
will return only the elements which are under the given node.
sidemenu.childNodes
will return both elements as well as text nodes, which is not the list of items you require. If you check the value returned by lastChild
it would be an empty text node and not an li
. That is why all the li
were getting removed.
function clearAll() {
var sidemenu = document.getElementById('side_menu');
while (sidemenu.children.length > 1) {
sidemenu.removeChild(sidemenu.lastChild);
}
}
Upvotes: 6
Reputation: 8488
To keep the first child change
sidemenu.childNodes.length > 1
to
sidemenu.childNodes.length > 2
function clearAll() {
var sidemenu = document.getElementById('side_menu');
while (sidemenu.childNodes.length > 2) {
sidemenu.removeChild(sidemenu.lastChild);
}
}
Upvotes: 0
Reputation: 647
If you use jQuery you could do this:
$('#side_menu li:not(:first)').remove();
Upvotes: -1