Skip to content

Inserting into the DOM

When you want to insert new DOM elements, there are several methods you can use depending on your needs.

Inserting Existing Nodes

You can use appendChild to add an existing node to the end of a parent node's child list:

javascript
let js = document.getElementById('js');
let list = document.getElementById('list');
list.appendChild(js);

This will move the js node to the end of the list and remove it from its original position.

Creating and Inserting New Nodes

To create a new node and insert it, use createElement:

javascript
let list = document.getElementById('list');
let haskell = document.createElement('p');
haskell.id = 'haskell';
haskell.innerText = 'Haskell';
list.appendChild(haskell);

This adds a new <p> element with the text "Haskell" to the list.

Dynamic CSS Insertion

You can dynamically create a <style> element and insert it into the <head>:

javascript
let d = document.createElement('style');
d.setAttribute('type', 'text/css');
d.innerHTML = 'p { color: red }';
document.getElementsByTagName('head')[0].appendChild(d);

Using insertBefore

To insert a node before a reference node, use insertBefore:

javascript
let list = document.getElementById('list');
let ref = document.getElementById('python');
let haskell = document.createElement('p');
haskell.id = 'haskell';
haskell.innerText = 'Haskell';
list.insertBefore(haskell, ref);

This inserts the haskell node before the python node.

Example Exercise

Given the following HTML structure:

html
<ol id="test-list">
    <li class="lang">Scheme</li>
    <li class="lang">JavaScript</li>
    <li class="lang">Python</li>
    <li class="lang">Ruby</li>
    <li class="lang">Haskell</li>
</ol>

You can sort the list by creating an array, sorting it, and then re-inserting the nodes:

javascript
// Sort list:
let list = document.getElementById('test-list');
let items = Array.from(list.children);

items.sort((a, b) => a.innerText.localeCompare(b.innerText));

// Clear the list and re-insert sorted items
list.innerHTML = '';
items.forEach(item => list.appendChild(item));

// Test the sorting
(function () {
    let arr = [];
    for (let i = 0; i < list.children.length; i++) {
        arr.push(list.children[i].innerText);
    }
    if (arr.toString() === ['Haskell', 'JavaScript', 'Python', 'Ruby', 'Scheme'].toString()) {
        console.log('test passed!');
    } else {
        console.log('test failed: ' + arr.toString());
    }
})();
Inserting into the DOM has loaded