Create and Insert an Element

Create and Insert an Element

createElement makes a detached DOM element. Set its text, then append it to a chosen parent to display a new student in a class list. Creation and insertion are separate steps.

Before this topic, review Respond to an Event if its terms are unfamiliar.

What you’ll learn

  • Explain create and insert an element through the school example.
  • Trace the shown operations and distinguish their result from displayed output.
  • Make the practice change and explain its consequence: The student's label changes, but exactly one element is inserted.

Work through the school example

This is JavaScript in a browser. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.

Create this markup in a separate index.html, then place the JavaScript in a script after these elements. Use this isolated practice page so the selectors refer to its markup.

<ul id="students"></ul>

JavaScript · browser · complete script for the supplied markup

const item = document.createElement("li");
item.textContent = "Diya";
document.querySelector("#students").append(item);
console.log(document.querySelector("#students").children.length);

Expected output

1

JavaScript Create Elements – A Complete Guide

Modern web development thrives on dynamic interactivity. Whether you're building a to-do app, a comment section, or a drag-and-drop dashboard, at the heart of these features is one powerful capability: dynamically creating HTML elements using JavaScript.

In this tutorial, you'll learn how to create HTML elements using the document.createElement() method, manipulate their content and attributes, and insert them into the DOM — all without writing a single line of HTML!

Why Create Elements Dynamically?

There are times when static HTML just doesn’t cut it — maybe you're fetching data from an API, generating items based on user input, or building reusable components. Instead of hardcoding elements, JavaScript lets you create them on the fly.

Step 1: The Basics – document.createElement()

Let’s begin with the simplest example. Suppose you want to add a new paragraph to your page:

const newPara = document.createElement("p");
newPara.textContent = "This paragraph was created using JavaScript!";
document.body.appendChild(newPara);
This paragraph was created using JavaScript!

Understanding the Code

  • document.createElement("p"): Creates a new empty <p> element.
  • textContent: Adds text inside the paragraph.
  • appendChild(): Inserts the element into the DOM, here as the last child of the <body>.

Step 2: Adding Attributes to New Elements

Now, let’s style and identify the element using attributes:

const btn = document.createElement("button");
btn.textContent = "Click Me";
btn.setAttribute("id", "dynamicBtn");
btn.style.backgroundColor = "teal";
btn.style.color = "white";
document.body.appendChild(btn);
[Button appears styled with teal background and white text]

Step 3: Nesting Elements (Creating Tree Structures)

Often, you’ll want to create not just one element but a group — say a <div> containing a <h3> and a <p>:

const card = document.createElement("div");
card.className = "card";

const heading = document.createElement("h3");
heading.textContent = "Dynamic Card Title";

const desc = document.createElement("p");
desc.textContent = "This is the card description.";

card.appendChild(heading);
card.appendChild(desc);
document.body.appendChild(card);
[Card appears with a heading and paragraph inside]

Step 4: Inserting at Specific Positions

You’re not always limited to appending at the end. Use insertBefore() or before(), after(), prepend() methods:

const list = document.querySelector("ul");
const newItem = document.createElement("li");
newItem.textContent = "I'm a new list item!";
list.prepend(newItem); // inserts at the top of the list

Step 5: Creating Elements Using innerHTML (Caution!)

Though not recommended for security reasons, you can also use innerHTML if you're building complex structures quickly:

const wrapper = document.createElement("div");
wrapper.innerHTML = `
  <h4>Title</h4>
  <p>Generated using innerHTML</p>
`;
document.body.appendChild(wrapper);

Step 6: Handling Events on Dynamically Created Elements

Adding a button is great, but what if you want it to do something?

const alertBtn = document.createElement("button");
alertBtn.textContent = "Alert Me!";
alertBtn.addEventListener("click", () => {
  alert("Button was clicked!");
});
document.body.appendChild(alertBtn);

Real-World Example: Add Items to a List from Input

// HTML: <input id="itemInput"> <button id="addBtn">Add</button> <ul id="itemList"></ul>

document.getElementById("addBtn").addEventListener("click", () => {
  const value = document.getElementById("itemInput").value;
  const li = document.createElement("li");
  li.textContent = value;
  document.getElementById("itemList").appendChild(li);
});

Best Practices

  • Prefer textContent over innerHTML for plain text to avoid XSS attacks.
  • Use classList.add() instead of className for multiple classes.
  • Always sanitize user input if using it inside innerHTML.

Summary

Creating elements dynamically in JavaScript opens a world of flexibility — from generating user interfaces on-the-fly to responding instantly to user interactions. Using document.createElement(), you can construct entire component trees, inject them into the DOM, and breathe life into static pages.

Mastering this topic is a gateway to building modern, interactive, JavaScript-powered web apps.

Recognize the important boundary

Appending an existing node moves it rather than copying it. Use textContent for user-provided labels.

Try a small variation

JavaScript · original source for practice

const item = document.createElement("li");
item.textContent = "Diya";
document.querySelector("#students").append(item);
console.log(document.querySelector("#students").children.length);

Your task: Replace 'Diya' with 'Saira'. Predict the result before running the edited program.

The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.

Markup used by this section:

<ul id="students"></ul>

Worked answer and reasoning

The student's label changes, but exactly one element is inserted.

Markup for this edited program:

<ul id="students"></ul>

JavaScript · complete worked variation

const item = document.createElement("li");
item.textContent = "Saira";
document.querySelector("#students").append(item);
console.log(document.querySelector("#students").children.length);

Expected output

1

Predict the original program

JavaScript · original program for this question

const item = document.createElement("li");
item.textContent = "Diya";
document.querySelector("#students").append(item);
console.log(document.querySelector("#students").children.length);

Markup used by this section:

<ul id="students"></ul>
In the browser, what does the original JavaScript example display, in order?
Choose one answer. You can try again.

Answer and explanation

1

createElement makes a detached DOM element. Set its text, then append it to a chosen parent to display a new student in a class list. Creation and insertion are separate steps. Appending an existing node moves it rather than copying it. Use textContent for user-provided labels.

Keep the useful idea

createElement makes a detached DOM element. Set its text, then append it to a chosen parent to display a new student in a class list. Creation and insertion are separate steps.

Check your variation against this explanation: The student's label changes, but exactly one element is inserted.

Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Remove a Chosen Element →