Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Adding Elements to the DOM

Hello! Welcome back to your front-end development course.

In our last lesson, we learned how to dynamically change the appearance of elements by adding, removing, and toggling their CSS classes with classList. This is perfect for altering existing content. But what about when the content itself doesn't exist yet?

Today, we'll tackle that exact scenario. This lesson addresses the learning outcome: Create new elements and append them to the DOM using createElement and appendChild. This is the core skill for building truly dynamic web applications, where content like comments, product listings, or notifications are generated on the fly based on user actions or data.

From a design perspective, think of this as programming the creation of repeatable components. When you design a user profile card or a list item in Figma, you create it once. In code, we'll write the instructions to create that element whenever we need it, as many times as we need it.

1. The Two-Step Process: Create, then Append

Creating and adding new elements to a webpage is a two-step process:

  1. Create the element: You use a JavaScript method to manufacture a new HTML element. This element exists in your script's memory but is not yet visible on the page. It's like having a component from your design library ready to go, but not yet placed on an artboard.
  2. Append the element: You select an existing element on the page to act as a "parent" and then attach, or "append," your newly created element as its "child." This makes the new element appear on the page.

Let's look at each step.

2. Step 1: Creating Elements with document.createElement()

The first step is to create an element using the document.createElement() method. You simply pass it a string with the tag name of the element you want to create.

This video provides a clear, quick introduction to this method.

Document.createElement() - Javascript DOM

This video from the dcode channel, "Document.createElement() - Javascript DOM", demonstrates how to use this method to create new elements.

Please watch the following segments: Introduction (00:00 - 00:29): Get a quick overview of what createElement does. Creating a new HTML element (00:29 - 01:44): See how to create a <div> and store it in a variable. Creating an input element (02:21 - 02:34): Note how the same method can create any type of HTML element.

As you saw, the syntax is straightforward:

// Creates a <div> element
const newDiv = document.createElement('div');

// Creates a paragraph element
const newParagraph = document.createElement('p');

// Creates a list item element
const newListItem = document.createElement('li');

At this point, these elements exist only as JavaScript objects. If you were to run this code, you wouldn't see anything change on your webpage yet. To make them appear, we need to perform the second step.

For a detailed reference, the MDN documentation is the industry standard.

Document: createElement() method - Web APIs | MDN

The MDN Web Docs for document.createElement() is the definitive guide. It's a good idea to get familiar with reading official documentation.

Read the introduction at the top of the page, the "Syntax" section, and the "Basic example". Don't worry about the "Web component example" for now. Notice how the example creates a div, then creates a text node to put inside it.

3. Step 2: Appending Elements with appendChild()

Once you've created an element, you need to add it to the Document Object Model (DOM). The appendChild() method lets you do this. You call this method on the parent element where you want to insert your new element.

The following video demonstrates this process by building a list, which is a very common use case.

appendChild() - JavaScript DOM Tutorial For Beginners

This dcode video, "appendChild() - JavaScript DOM Tutorial For Beginners", focuses on how to attach your newly created elements to the page.

Watch the introduction and the first example: Introduction to appendChild() (00:00 - 01:02): Understand the parent-child relationship. Appending a single element (01:02 - 03:38): Pay close attention to the sequence: get the parent, create the child, set the child's content, and finally, append the child.

The process shown in the video is a fundamental pattern in front-end development:

  1. Select the parent: const parentElement = document.querySelector('#my-list');
  2. Create the child: const newChildElement = document.createElement('li');
  3. Add content/attributes to the child: newChildElement.textContent = 'New item';
  4. Append the child: parentElement.appendChild(newChildElement);

appendChild() will always add the new element as the last child of the parent.

The MDN documentation for appendChild() provides further details and is a valuable resource to have on hand.

Node: appendChild() method - Web APIs | MDN

The MDN page for Node: appendChild() explains the method's behavior in detail.

Please read the introduction, the "Syntax" section, and the first example, "Append a paragraph to the body". Notice the important note that if you append an element that is already on the page, it will be moved, not copied.

4. Your Turn: Building a Dynamic To-Do List

Let's combine everything you've learned to build a simple but powerful feature: a to-do list. The user will type a task into an input field, click a button, and the task will appear in the list. This exercise brings together element selection, event handling, and dynamic element creation.

Your Goal: Write the JavaScript to create a new list item (<li>) and add it to the to-do list (<ul>) when the "Add Task" button is clicked.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic To-Do List</title>
    <style>
        body { font-family: sans-serif; background-color: #f0f2f5; display: grid; place-content: center; min-height: 100vh; margin: 0; }
        .container { background: #fff; padding: 2rem; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 400px; }
        h1 { color: #333; }
        .input-group { display: flex; margin-bottom: 1rem; }
        #task-input { flex-grow: 1; border: 1px solid #ccc; padding: 0.5rem; border-radius: 4px 0 0 4px; }
        #add-task-btn { background-color: #007bff; color: white; border: none; padding: 0.5rem 1rem; cursor: pointer; border-radius: 0 4px 4px 0; }
        #task-list { list-style-type: none; padding: 0; }
        #task-list li { background: #f9f9f9; padding: 0.75rem; border-bottom: 1px solid #eee; }
        #task-list li:last-child { border-bottom: none; }
    </style>
</head>
<body>

    <div class="container">
        <h1>My To-Do List</h1>
        <div class="input-group">
            <input type="text" id="task-input" placeholder="e.g., Design the new homepage">
            <button id="add-task-btn">Add Task</button>
        </div>
        <ul id="task-list">
            <!-- New tasks will be added here! -->
        </ul>
    </div>

    <script>
        // 1. Select the necessary elements
        const taskInput = document.querySelector('#task-input');
        const addTaskBtn = document.querySelector('#add-task-btn');
        const taskList = document.querySelector('#task-list');

        // 2. Add a click event listener to the button
        addTaskBtn.addEventListener('click', () => {
            // 3. Get the text from the input field
            const taskText = taskInput.value.trim(); // .trim() removes whitespace from ends

            // 4. Check if the input is not empty
            if (taskText !== '') {
                // --- YOUR CODE GOES HERE ---
                
                // a. Create a new list item element ('li')
                
                // b. Set the textContent of the new list item to be the taskText
                
                // c. Append the new list item to the taskList (the <ul>)
                
                // d. Clear the input field for the next task
                taskInput.value = '';
            }
        });
    </script>

</body>
</html>

Your Task:

  1. Copy the code above into a new HTML file.
  2. Locate the // --- YOUR CODE GOES HERE --- comment inside the addEventListener function.
  3. Implement the three missing steps (a, b, and c) using createElement, textContent, and appendChild.

When you're finished, you should be able to type into the input, click the button, and see your new task appear in the list.

Click here to see the solution
// a. Create a new list item element ('li')
const newListItem = document.createElement('li');

// b. Set the textContent of the new list item to be the taskText
newListItem.textContent = taskText;

// c. Append the new list item to the taskList (the <ul>)
taskList.appendChild(newListItem);

Conclusion

Excellent work! You've just built the core functionality of countless web applications. The ability to dynamically create and add elements to the page is a superpower in front-end development.

Key Takeaways:

  • Creating and adding elements is a two-step process: createElement() then appendChild().
  • document.createElement('tagName') creates a new element that exists only in your script's memory.
  • parentElement.appendChild(newElement) attaches the new element to the DOM, making it visible as the last child of the parent.
  • This pattern is essential for displaying data that comes from users (like in our to-do list) or from a server.

In our exercise, we used addEventListener to kick off our logic. In the next lesson, we will dive deeper into handling user events. We'll explore different event types like click, submit, and input, and learn how to use the event object to create even more responsive and interactive user experiences.

Can't find a good explanation? Sign up and we'll make it for you

Sign up