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.
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.
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.
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 .
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With