JavaScript DOM Manipulation

Besides changing existing elements, JavaScript can create new ones and add or remove them on the page.


Create and add an element

<ul id="list">
  <li>Apple</li>
</ul>
const list = document.getElementById("list");

const item = document.createElement("li");   // 1. create
item.textContent = "Banana";                  // 2. fill
list.append(item);                             // 3. add to the page
The list after the code runs
  • Apple
  • Banana

MethodWhat it does
parent.append(el)Adds at the end
parent.prepend(el)Adds at the start
el.before(x), el.after(x)Adds next to an element
el.remove()Removes the element
el.cloneNode(true)Makes a copy (with children)
parent.replaceChildren()Removes all the children

Build a list from an array

const fruits = ["Apple", "Banana", "Mango"];
const ul = document.createElement("ul");

for (const f of fruits) {
  const li = document.createElement("li");
  li.textContent = f;
  ul.append(li);
}
document.body.append(ul);
console.log(ul.children.length);
Output of the above program is

3


Remove an element

const first = document.querySelector("li");
first.remove();

innerHTML or createElement?

list.innerHTML += "<li>Orange</li>";       // short, but re-creates all children

innerHTML is short, but it rebuilds everything inside, and it is unsafe with text from visitors (XSS). createElement with textContent is safer and keeps the events of existing elements.

Note: When you add many elements, build them first and add them in one go (with a DocumentFragment or by appending to a parent that is not on the page yet). It is faster.

Summary

  • createElement makes an element, append or prepend puts it on the page.
  • remove() deletes an element.
  • Prefer textContent over innerHTML for user text.
  • Next: DOM EventListener.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.