Example 1 — Create, Set Text, Append
Build a div, give it text, then attach it to a parent.
const parent = document.createElement("section");
const el = document.createElement("div");
el.textContent = "Hi there and greetings!";
parent.appendChild(el);
console.log(parent.children.length); // 1
console.log(el.tagName); // "DIV"
console.log(el.textContent); // "Hi there and greetings!" How It Works
- Create a parent. A
sectionwill hold the new node. - Create the element.
createElement("div")returns a detacheddiv. - Set content.
textContentis the simplest way to add text. - Append. Until
appendChild, the element is not in any tree.

