Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 575
miestasmia Avatar asked Jan 12 '13 14:01

miestasmia


People also ask

What is remove child method in Javascript?

removeChild() The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node. Note: As long as a reference is kept on the removed child, it still exists in memory, but is no longer part of the DOM. It can still be reused later in the code.

How do you remove an element from a child?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.

How do I get rid of my last child?

First, get the ul element with the id menu by using the getElementById() method. Then, remove the last element of the ul element by using the removeChild() method. The menu. lastElementChild property returns the last child element of the menu .

What is first element child in Javascript?

firstChild returns the first child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes. firstElementChild returns the first child element (not text and comment nodes).


1 Answers

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. 
like image 124
Alex Avatar answered Oct 22 '22 20:10

Alex