Syntax
document.createElement(tag)
parent.appendChild(child)
element.textContent = textExamples
Creating and Appending an Element
Building a new element from scratch and adding it to the page.
const newItem = document.createElement("li");
newItem.textContent = "New list item";
newItem.classList.add("list-item");
const list = document.querySelector("#myList");
list.appendChild(newItem);
// append() is a newer alternative that also accepts plain strings
list.append("Some plain text", newItem);textContent vs innerHTML
The important security and behavior difference between the two.
const div = document.querySelector("#output");
const userInput = "<img src=x onerror='alert(1)'>";
div.textContent = userInput; // SAFE - displayed as literal text, not executed
div.innerHTML = userInput; // DANGEROUS if userInput is untrusted - can execute scriptsRemoving Elements
Cleanly removing elements from the DOM.
const item = document.querySelector("#tempMessage");
item.remove(); // modern, simple way to remove an element
// Older approach, still seen in some codebases:
// item.parentNode.removeChild(item);Best practices
- Use textContent instead of innerHTML whenever you are inserting plain text, especially anything derived from user input, to avoid XSS vulnerabilities
- Only use innerHTML with content you fully trust and control, or after properly sanitizing it
- Use element.remove() for removing an element - it is simpler than the older parentNode.removeChild() pattern
- Batch multiple DOM insertions where possible (e.g., building a DocumentFragment) instead of appending one element at a time, for better performance on large updates
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification