user4729539
user4729539

Reputation:

Remove child node except first using javascript

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

Answers (5)

Mike Lei
Mike Lei

Reputation: 41

Use Element.replaceChildren().

sidemenu.replaceChildren(sidemenu.firstElementChild);

Upvotes: 2

Rahul Desai
Rahul Desai

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

Anbarasan
Anbarasan

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

Zee
Zee

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

user4341206
user4341206

Reputation: 647

If you use jQuery you could do this:

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

Upvotes: -1

Related Questions