问题描述
我正在尝试使用DOM 删除
。但由于某些原因它不起作用。 ol
中的第一个 li
removeChild之()
I'm trying to remove the first li
in an ol
using the DOM removeChild()
. But for some reason it doesn't work.
这是我的javascript:
This is my javascript:
document.getElementById('queue').removeChild(
document.getElementById('queue').childNodes[0]
);
这是我的HTML:
<ol id="queue">
<li>Surprised Kitty (Original)<span class="nodisplay">0Bmhjf0rKe8</span></li></ol>
我试过警告 childNodes [0]
,它返回 [Object Text]
,这似乎有点奇怪,当我只期待对象时。
I tried alerting the childNodes[0]
, and it returns [Object Text]
, which seems a bit weird, when I was expecting just the object.
希望我一直很清楚。
推荐答案
在< ol id =queue> ;
和< li>
标记是空格和换行符。这些组成了一个文本节点。因此, #queue
元素的第一个子元素是文本节点。
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 #queue
element is therefore a text node.
您可以使用属性而不是 .childNodes
,它只考虑元素节点,或迭代所有子节点,直到找到第一个 li
节点,如。
You can use the .children
property instead of .childNodes
, it only considers element nodes, or iterate over all child nodes until you find the first li
node, like suggested by dystroy.
这篇关于在javascript中删除第一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!