HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

7) The Document Object Model Lesson

Create and Place New DOM Elements with JavaScript

21 min to complete · By Ian Currie

Sometimes you want to do more than just modify DOM Elements, sometimes you want to create your own elements and add them to the DOM. Perhaps in response to a user action, or perhaps you want to create a game or some other interactive experience. This lesson will teach you how to create DOM elements, add them to the DOM and choose where to insert them.

How to Use the .createElement() Method

There is one method on the document object that you'll need to know to create new elements: .createElement(). Here is the method signature:

document.createElement(tagName, options);

This method is called on the document and takes two arguments:

  • a string containing the tag name of the element you would like to create. For example, if you wanted to create a <button> </button> element, you would pass in the string "button" as the first argument.
  • an optional object containing options for the element you would like to create, which you don't need to worry about for this introductory lesson.

So, if you would like to add in a <button> </button> element to your HTML, then you would first create the element using the method something like this:

let btn = document.createElement("button");
btn.textContent = "Click Me!";

You've created a button element and set its text content to "Click Me!". However, it's not visible yet. It's actually not in the document yet. So if you looked for it with a .querySelector() method, for example, you wouldn't find it.

How to Add a Newly Created Element to the DOM

In an existing document, there may be hundreds of elements structured as parents, siblings and children. To accommodate the various ways you might want to add an element to the document tree, there are a few different methods you can use to add an element to the DOM.

Here are a few of the most common ones:

Method Called On Arguments Description
appendChild Parent Element childElement Adds a node to the end of the list of children of a specified parent node.
insertBefore Parent Element newElement, referenceElement Inserts a node before the reference node as a child of a specified parent node.
replaceChild Parent Element newChild, oldChild Replaces an old child node with a new child node within a parent node.
insertAdjacentElement Sibling Element position, element Inserts a given element node at a given position relative to the element it is invoked upon.

In the next few sections, you'll learn how to use them.

Add an Element to the End of a Parent Element

A commonly used method to add the newly created element to the DOM is to append it as the last child of another element using the .appendChild() method. This will place the element at the end of the parent element's children in the document's structure:

let btn = document.createElement("button");
btn.textContent = "Click Me!";
document.body.appendChild(btn);

In this example, you've created a button element and set its text content to "Click Me!". Then you've appended it to the end of the body. So no matter where you run this code, it will add a button to the end of the body of the page you're on. Because all pages have a <body> element accessible from the document.

Illustration of a lighthouse

Sometimes adding to the end of the body doesn't mean that it will end up at the end of the visible page. Perhaps the page has some CSS that means that it will be hidden.

Remember that you don't have to make it the body. If you select any element, you can call .appendChild() on that element to add any element to that one.

let container = document.getElementById("container");
container.appendChild(btn);

You can also create a whole list of elements and append a nested structure to the body:

let list = document.createElement("ul");

for (let i = 0; i < 3; i++) {
  let listItem = document.createElement("li");
  listItem.textContent = `This is list item ${i}`;
  list.appendChild(listItem);
}

document.body.appendChild(list);

In this example, you've created a list element and then used a for loop to create three list items and append them to the list. Then you've appended the list to the body. Are you starting to see how all of this comes together?

Add an Element to the Beginning of a Parent Element

The .insertBefore() method can be used to add an element before a specific child within a parent element. It's not limited to just the beginning; you can use any child as the reference point for insertion. This method is called on the parent element and takes two arguments:

  • the first argument is the element you would like to add
  • the second argument is the element you would like to add it before

So, if you wanted to add a button to the beginning of the body, you could do it like this:

let btn = document.createElement("button");
btn.textContent = "Click Me!";
document.body.insertBefore(btn, document.body.firstChild);

In this example, you've created a button element and set its text content to "Click Me!". Then you've inserted it before the first child of the body. So no matter where you run this code, it will add a button to the beginning of the body of the page you're on.

Add an Element Before or After a Sibling Element

The methods covered so far require you locate the parent element of the element you want to add. But you can also add an element before or after an element using the .insertAdjacentElement() method. This method takes two arguments:

  • the first argument is a string that acts as an option that specifies where you would like to insert the element. It can be one of the following values:
    • "beforebegin": Before the element itself.
    • "afterbegin": Just inside the element, before its first child.
    • "beforeend": Just inside the element, after its last child.
    • "afterend": After the element itself.
  • the second argument is the element you would like to add

To see this in action, imagine this basic HTML:

<body>
  <div id="label">This is a label</div>
</body>

Here is the JavaScript to demonstrate the different ways you can insert the button.

let label = document.getElementById("label");
let btn = document.createElement("button");
btn.textContent = "Click Me!";

label.insertAdjacentElement("beforebegin", btn);
document.body;
/*
<body>
  <button>Click me!</button>
  <div id="label">This is a label</div>
</body>
*/

label.insertAdjacentElement("afterbegin", btn);
document.body;
/*
<body>
  <div id="label">
    <button>Click me!</button>
    This is a label
  </div>
</body>
*/

label.insertAdjacentElement("beforeend", btn);
document.body;
/*
<body>
  <div id="label">
    This is a label
    <button>Click me!</button>
  </div>
</body>
*/

label.insertAdjacentElement("afterend", btn);
document.body;
/*
<body>
  <div id="label">This is a label</div>
  <button>Click me!</button>
</body>
*/

As you can see, the .insertAdjacentElement() method is very flexible. You can insert an element before or after another element, or you can insert it as the first or last child of another element. All while only having to reference just one element.

Colorful illustration of a light bulb

You can insert the same element various times, but that's not going to duplicate the element. It will just move it around.

How to Replace an Element

You can also replace an element with another element using the .replaceChild() method. It's slightly convoluted because you need to call the method on the parent element, and also pass in the item to be replaced.

If you had an HTML element with an id of item-to-be-replaced:

<ul>
  <div id="item-to-be-replaced"> This item should be replaced</div>
</ul>

You can replace the item with the following JavaScript:

let itemToBeReplaced = document.getElementById("item-to-be-replaced");
let replacementItem = document.createElement("li");
replacementItem.id = "item-to-be-replaced";
replacementItem.textContent = "This is the replacement item";

itemToBeReplaced.parentNode.replaceChild(replacementItem, itemToBeReplaced);

In this example, you've created a new list item element and set its text content to "This is the replacement item". You've also set it's id attribute in case you want to replace it in the future again.

Then to replace the item, you need to call the .replaceChild() method on the parent node of the item to be replaced. To get the parent node, you can use the .parentNode property.

From there, you just chain on a call to .replaceChild(), passing in the replacement item as the first argument and the item to be replaced as the second argument.

How to Add Rows to a Table

There is an interesting element in HTML called the table which will now be examined as a great way to understand nesting and element manipulation. It looks like this in raw HTML:

<table>
  <tr>
    <th>City</th>
    <th>Temperature</th>
    <th>Scale</th>
  </tr>
  <tr>
    <td>San Francisco</td>
    <td>70</td>
    <td>Fahrenheit</td>
  </tr>
  <tr>
    <td>Jerusalem</td>
    <td>28</td>
    <td>Celsius</td>
  </tr>
</table>

This renders to an HTML that will look something like this:

City Temperature Scale
San Francisco 70 Fahrenheit
Jerusalem 28 Celsius

Each row is represented by a <tr> (table row) and each item in each row is represented by either a <th> or a <td>. <th> stands for "table header" while <td> stands for "table data".

Try and build a new table row and append it to the table. This will require you to first append three elements to the table row, and then append the table row to the table. Start out with the table HTML loaded in the browser, write the JavaScript in a text editor, and try it out on the browser console.

Illustration of a lighthouse

You'd be surprised how easy it is to get mixed up when doing these types of operations. Take it step by step and be sure to test it out at each step.

let table = document.querySelector("table");
let newRow = document.createElement("tr");

let city = document.createElement("td");
city.textContent = "New York";

let temperature = document.createElement("td");
temperature.textContent = "80";

let scale = document.createElement("td");
scale.textContent = "Fahrenheit";

newRow.appendChild(city);
newRow.appendChild(temperature);
newRow.appendChild(scale);

table.appendChild(newRow);

Reading Documentation

You've already gone through the .insertBefore() method, but in this section. you'll be walked through the documentation for this method. This is a good chance to get familiar with the structure of reference materials and how it explains things concisely.

Being able to navigate documentation is an essential skill in front-end development. There is simply too much information, too many methods, arguments, inconsistencies, new standard, old standards, etc. to memorize everything. So you'll need to get good at finding the information you need.

Open this link up in a new tab and examine the documentation for the .insertBefore() method.

The first thing you'll see is a brief description of the method with any important information.

Then comes the syntax. This is the signature of the method. It tells you the name of the method, the arguments it takes, and the return value. You'll also see if it raises any exceptions.

Then you'll find some examples to show you different aspects of how to use the method.

Then comes the specifications section, which links to the relevant standards documents.

Then comes the browser compatibility section, which shows you which browsers support this method and from which version they support it. This is very important to check if you're using a new method or feature!

You'll also note that in the left sidebar you can easily navigate to other methods of the Node object, such as .appendChild() and .replaceChild(). You'll also see related properties, objects, and interfaces.

The MDN documentation is a great, detailed and technical resource for reference information about JavaScript and the DOM. You'll be using it a lot, so it's worth getting familiar with it! You can also use the search bar at the top of the page to search for any method or property you're looking for.

It's also worth noting that the MDN documentation is a community effort. So if you see something that is incorrect or missing, you can contribute to it by clicking the "Edit this page" link at the bottom of the page.

Summary: How to Create DOM Elements Using the createElement Method

You've just learned how to create and place DOM elements with JavaScript, unlocking dynamic content generation in your web development endeavors. In this lesson you've:

  • Got acquainted with .createElement() for creating new DOM elements.
  • Understood that newly created elements must be explicitly added to the document to be visible, using methods like appendChild or insertBefore.
  • Discovered multiple ways to insert elements relative to other elements giving you flexibility in structuring your content.
  • Appreciated the importance of reading documentation, particularly using MDN as a go-to resource for technical details on DOM methods.

Remember to reference the documentation for specifics and compatibility checks as you continue to use these methods in real-world projects!