Javascript 在javascript中删除第一个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14294518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove first child in javascript
提问by miestasmia
I'm trying to remove the first liin an olusing the DOM removeChild(). But for some reason it doesn't work.
我正在尝试使用 DOM删除第li一个。但由于某种原因它不起作用。olremoveChild()
This is my javascript:
这是我的javascript:
document.getElementById('queue').removeChild(
document.getElementById('queue').childNodes[0]
);
And this is my HTML:
这是我的 HTML:
<ol id="queue">
<li>Surprised Kitty (Original)<span class="nodisplay">0Bmhjf0rKe8</span></li></ol>
I tried alerting the childNodes[0], and it returns [Object Text], which seems a bit weird, when I was expecting just the object.
我尝试提醒childNodes[0],它返回[Object Text],这看起来有点奇怪,当我只期待对象时。
Hope I've been clear.
希望我已经清楚了。
回答by Alex
Try this one-liner:
试试这个单线:
document.getElementById('queue').removeChild(document.getElementById('queue').getElementsByTagName('li')[0]);
With expanded explanation:
扩展说明:
var queue = document.getElementById('queue'); // Get the list whose id is queue.
var elements = queue.getElementsByTagName('li'); // Get HTMLCollection of elements with the li tag name.
queue.removeChild(elements[0]); // Remove the child from queue that is the first li element.
回答by Felix Kling
Between the <ol id="queue">and the <li>tag are spaces and a line break. These make up a text node. The first child of the #queueelement is therefore a text node.
之间的<ol id="queue">和<li>标签是空格和换行。这些组成了一个文本节点。#queue因此元素的第一个子元素是一个文本节点。
You can use the .childrenproperty instead of .childNodes, it only considers element nodes, or iterate over all child nodes until you find the first linode, like suggested by dystroy.
您可以使用.children属性代替.childNodes,它只考虑元素节点,或迭代所有子节点,直到找到第一个li节点,如dystroy 建议的那样。
回答by Denys Séguret
Child nodes aren't just the elements you think about but also the text nodes. You can iterate over the nodes and remove the first LI.
子节点不仅是您想到的元素,也是文本节点。您可以遍历节点并删除第一个LI.
var p = document.getElementById('queue');
for (var i=0; i<p.childNodes.length; i++) {
if (p.childNodes[i].tagName=='LI') {
p.removeChild(p.childNodes[i]);
break;
}
}
Note that this is more an explanation than the most practical solution. Javascript has other iteration solutions for you, among them getElementsByTagName, so you may do this :
请注意,这与其说是最实用的解决方案,不如说是一种解释。Javascript 为您提供了其他迭代解决方案,其中包括getElementsByTagName,因此您可以这样做:
var p = document.getElementById('queue');
p.removeChild(p.getElementsByTagName('li')[0]);
回答by kennebec
remove all lists contained by queue:
删除队列包含的所有列表:
var list=document.getElementById('queue');
list.removeChild(list.getElementsByTagName('li')[0]);

