Javascript: Add & Remove HTML Elements

In this post, I'm going to walk through the simplest possible example of how Javascript enables the creation and deletion of HTML elements. Using a list, we will access elements based on their tag name, add a new item to the list, and delete an item from the list. This tutorial is designed to be beginner friendly. 

Let's start by creating a simple list file in HTML. Mine looks like this: 

<ul id="list">
    <li id="one">One</li>
    <li id="two">Two</li>
    <li id="three">Three</li>
    <li id="four">Four</li>
</ul>

Next, we'll open this file's path in the browser. For example, the URL might look something like this: 

file:///Users/<yourname>/Desktop/list.html

Adding Elements 

Now right-click, selecting "Inspect" and open up the "Console" tab so we can begin writing some Javascript. The first thing we'll do is add an item to the list named Five. This comes in a few steps: 

1. Access the parent element using the method getElementsByTagName and save it as a variable named "list."

list = document.getElementsByTagName('ul')[0];

2. Create a new item using the method createElement and save it as a variable named "newItem."

newItem = document.createElement('li');

3. Create some text to place in that new element. We'll add the word "Five" using the method createTextNode. Then we'll append this new text to our new Item! 

newText = document.createTextNode('Five');
newItem.appendChild(newText);

4. Finally, we'll use appendChild again, this time to add the new Item to the global list variable. When you hit enter on this final command, you should see the word Five displayed as your new list item! 

list.appendChild(newItem);

This is how my final output looks. 

Removing Elements 

Next, let's remove the third element from the list. In order to do so, we'll need three separate steps. 

1. Find the parent element, the same way we captured the <ul> tag in the previous example. 

list = document.getElementsByTagName('ul')[0];

2. Next, we will grab the list item "Three", identifying it as the third <li> element on the page. Note that we use the [2] flag because the list of items starts with 0. 

removeMe = document.getElementsByTagName('li')[2];

3. Finally, we will use the removeChild method to remove our selected value. After hitting enter, you should see the list automatically update, leaving only One, Two and Four. 

list.removeChild(removeMe);

This is the simplest possible implementation of these Javascript methods, but they can be extremely powerful. Now that you understand how to use them, go forth and wield your powers for good! Any questions? Let me know in the comments below!