Skip to content
Advertisement

Remove first child in javascript

I’m trying to remove the first li in an ol using the DOM removeChild(). But for some reason it doesn’t work.

This is my javascript:

document.getElementById('queue').removeChild(
    document.getElementById('queue').childNodes[0]
);

And this is my 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.

Hope I’ve been clear.

Advertisement

Answer

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.

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement