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
5 Answers
Reset to default 6use 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
版权声明:本文标题:Remove child node except first using javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744087942a2531486.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论