Skip to content
On this page

Deleting DOM Elements

Deleting a DOM node is straightforward. Here’s how you can do it:

Basic Deletion Method

To delete a node, obtain both the node and its parent, then use removeChild:

javascript
let self = document.getElementById('to-be-removed');
let parent = self.parentElement;
let removed = parent.removeChild(self);
console.log(removed === self); // true

Even after deletion, the node remains in memory and can be reinserted later.

Handling Multiple Deletions

When deleting multiple nodes, be cautious because the children property updates in real-time. For example:

javascript
let parent = document.getElementById('parent');
parent.removeChild(parent.children[0]); // Removes the first child
parent.removeChild(parent.children[0]); // Now this will remove what was previously the second child

Example Exercise

Given the following HTML structure:

html
<ul id="test-list">
    <li>JavaScript</li>
    <li>Swift</li>
    <li>HTML</li>
    <li>ANSI C</li>
    <li>CSS</li>
    <li>DirectX</li>
</ul>

You can remove nodes that are not related to web development:

javascript
// Remove unrelated nodes
let list = document.getElementById('test-list');
let items = Array.from(list.children);

items.forEach(item => {
    if (item.innerText === 'Swift' || item.innerText === 'ANSI C' || item.innerText === 'DirectX') {
        list.removeChild(item);
    }
});

// Test the remaining items
(function () {
    let arr = [];
    for (let i = 0; i < list.children.length; i++) {
        arr.push(list.children[i].innerText);
    }
    if (arr.toString() === ['JavaScript', 'HTML', 'CSS'].toString()) {
        console.log('test passed!');
    } else {
        console.log('test failed: ' + arr.toString());
    }
})();
Deleting DOM Elements has loaded