admin 管理员组

文章数量: 1086019

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?

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?

Share Improve this question edited Apr 13, 2015 at 10:26 Michael 3,3365 gold badges26 silver badges37 bronze badges asked Apr 13, 2015 at 10:24 user4729539user4729539 3
  • What does the corresponding HTML look like? – Anthony Grist Commented Apr 13, 2015 at 10:28
  • @AnthonyGrist it was removing all li tag – user4729539 Commented Apr 13, 2015 at 10:31
  • I know, you already said that in your question which I read. That's not really a response to my ment. – Anthony Grist Commented Apr 13, 2015 at 10:32
Add a ment  | 

5 Answers 5

Reset to default 6

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);
    }
}

Use Element.replaceChildren().

sidemenu.replaceChildren(sidemenu.firstElementChild);

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.

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);
    }
}

If you use jQuery you could do this:

$('#side_menu li:not(:first)').remove();

本文标签: Remove child node except first using javascriptStack Overflow