Creating, inserting and removing nodes from the DOM By Chloe

To show how to create, insert and remove nodes from the DOM. An ordered list has been made which begins with only two list items:

    let groceryList = document.querySelector('ul');

    let newItem = document.createElement('li');

    newItem.textContent = 'cheese';

    groceryList.appendChild(newItem);
    
In the grocery list example, we started with a unordered list with two list items (eggs and bread) in the HTML page.
Using the JS code shown, we selected the ul using the query selector and assigned it to a new variable (groceryList), we then created a new li item using the .createElement and assigned it to a variable call 'newItem', using the .textContent methd we assigned newItem to contain the text 'cheese'. Finally we used the .appendchild to add the new node (newItem) to the ul list i.e groceryList variable.

    let toDoList = document.getElementById('toDo');

    let newToDo = document.createElement('li');

    newToDo.textContent = 'Write code';

    toDoList.insertBefore(newToDo, toDoList.children[1]);
    
In the to-do list example, we started with a to-do list with two list items in the HTML page (Go Biking and laundry). We assigned the unordered list an id of toDo
In the JS code we used the .getElementById to retrieve the 'ul' and assigned to a variable called toDoList. After that, we created the newToDo variable and created a li element within it. We then used the .textContent method to assign 'write code' to the newToDo variable.
Finally we used the insertBefore method to insert the newToDo variable before the .children[1] (go biking) of the Ul i.e. toDoList.
        let rep = document.getElementById('replaceList');

        let rep1 = document.createElement('li');

        rep1.textContent = 'ooops';

        rep.replaceChild(rep1, rep.children[6]);
        
In this example, the last list item was originally 'replaced' but was replaced with 'ooops'.
We used the .replace method to do this, it takes two arguments. The first is the new node and the second is the node it is replacing. In this case, it is the 6th child of the unordered list - remember its starts counting from 0.
        let example = document.getElementById('removingNode');

        example.removeChild(example.children[3]);

        example.children[0].remove();

        
In this example, the orginal HTML text was a unordered list (id = removingNode) with list items 'Some, nodes, have, been, removed! Sorry!
Using the removeChild example we removed the third child of the unordered list, and with the .remove method we removed the first (zero index) of the unordered list, which then displays what you can see.
Click here to return back to The DOM cheatsheet!