简体   繁体   中英

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?

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

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

如果您使用jQuery,则可以执行以下操作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM