在javascript中删除第一个孩子 [英] Remove first child in javascript

查看:139
本文介绍了在javascript中删除第一个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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.

您可以使用 .children 属性而不是 .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中删除第一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆