Creating and Removing Elements

A lot of the time we need to create elements from JavaScript instead of writing them into the initial HTML. The DOM gives us methods to create elements, insert them, and remove them.

Creating Elements

The createElement method creates a new element. We can then set it up and add it to the page:

// Create a new paragraph element
const para = document.createElement("p");

// Configure the element
para.textContent = "This is a new paragraph.";
para.className = "intro";
para.id = "welcome-message";

// At this point, the element exists but isn't visible on the page
// It needs to be inserted into the DOM

We can also create text nodes directly, though we do not do that often:

const textNode = document.createTextNode("Hello, world!");

Inserting Elements

A created element does not show up on the page until we insert it into the DOM. There are several methods for that, and they differ in where the element goes:

appendChild

Adds an element as the last child of a parent:

const list = document.querySelector("ul");
const newItem = document.createElement("li");
newItem.textContent = "New item";

list.appendChild(newItem);  // Adds at the end of the list

append and prepend

These are newer methods. They can insert more than one node at a time, and they accept strings as well as elements:

const container = document.querySelector(".container");

// append adds to the end
container.append(element1, element2, "some text");

// prepend adds to the beginning
container.prepend(element1, "text at start");

before and after

Insert elements as siblings:

const existingItem = document.querySelector(".item");
const newItem = document.createElement("div");
newItem.textContent = "Inserted item";

existingItem.before(newItem);  // Insert before existing item
existingItem.after(newItem);  // Insert after existing item

insertBefore

This is the older way to insert an element before a specific child:

const parent = document.querySelector("ul");
const newItem = document.createElement("li");
const referenceItem = parent.querySelector(".special");

// Insert newItem before referenceItem
parent.insertBefore(newItem, referenceItem);

Removing Elements

The remove method removes an element from the DOM:

const item = document.querySelector(".delete-me");
item.remove();

The older way is to call removeChild on the parent:

const parent = document.querySelector("ul");
const child = parent.querySelector("li.delete-me");
parent.removeChild(child);

To remove all children from an element:

const container = document.querySelector(".container");

// Method 1: Set innerHTML to empty
container.innerHTML = "";

// Method 2: Remove children one by one
while (container.firstChild) {
  container.removeChild(container.firstChild);
}

// Method 3: Use replaceChildren with no arguments
container.replaceChildren();

Building Elements: A Complete Example

Here is an example that builds a user card:

function createUserCard(user) {
  const card = document.createElement("div");
  card.className = "user-card";

  const name = document.createElement("h2");
  name.textContent = user.name;

  const email = document.createElement("p");
  email.textContent = user.email;
  email.className = "email";

  const button = document.createElement("button");
  button.textContent = "Contact";
  button.addEventListener("click", () => {
    console.log(`Contacting ${user.email}`);
  });

  card.append(name, email, button);
  return card;
}

// Usage
const users = [
  { name: "Alice", email: "alice@example.com" },
  { name: "Bob", email: "bob@example.com" },
];

const container = document.querySelector("#users");
users.forEach((user) => {
  container.appendChild(createUserCard(user));
});

Creating elements inside a function and returning them is also how frameworks like React structure components.