Codectionary / Developer documentation / JavaScript

Creating and Modifying Elements

createElement() builds a new DOM element in memory, which can then be customized and inserted into the page with methods like appendChild() or append(). textContent sets plain text safely, while innerHTML parses and inserts HTML markup - which carries injection risks if the content includes untrusted user input.

Syntax

document.createElement(tag)
parent.appendChild(child)
element.textContent = text

Examples

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 scripts

Removing 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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation