How do you append plain text or HTML to a div element in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you append plain text or HTML to a div element in JavaScript?

message-square
0

To append plain text to a <div> element in JavaScript safely and non-destructively, use div.append(text) or div.appendChild(document.createTextNode(text)) (or div.textContent += text for simple text nodes), which escapes special characters automatically and prevents Cross-Site Scripting (XSS). To append HTML markup to a <div> without wiping existing child nodes or re-parsing the entire inner HTML, use div.insertAdjacentHTML("beforeend", htmlString) (or parse/sanitize untrusted HTML first with a sanitizer such as DOMPurify or build DOM nodes explicitly with document.createElement()).


1. Appending Plain Text Safely with .append() and createTextNode()

Use div.append(...) or document.createTextNode(...) when inserting user input, logs, or dynamic strings—unlike innerHTML, plain-text insertion treats <, >, and & as literal text rather than markup:

// Append plain text to a <div> without risking HTML injection
function appendPlainText(container, text) {
  if (!(container instanceof Element)) {
    throw new TypeError("Expected container to be a DOM Element.");
  }

  const safeText = String(text ?? "");
  container.append(safeText);
}

// Example usage:
const statusBox = document.querySelector("#status-box");
appendPlainText(statusBox, "User input <script>alert(1)</script> rendered as text.");
  • Prefer .append() over innerHTML +=: innerHTML += serializes, destroys, and re-parses all existing child elements, losing event listeners and input state.
  • Avoid textContent += on large containers repeatedly: Updating textContent on a large element replaces all child nodes at once; .append(text) appends a text node directly.

2. Appending HTML Markup with insertAdjacentHTML("beforeend", ...)

When you intentionally need to append HTML markup at the end of a <div>, call div.insertAdjacentHTML("beforeend", htmlString), which inserts parsed nodes after the last child without replacing existing children or breaking previously bound event listeners:

// Append an HTML snippet at the end of a <div> without wiping existing children
function appendHtmlSnippet(container, htmlString) {
  if (!(container instanceof Element)) {
    throw new TypeError("Expected container to be a DOM Element.");
  }
  if (typeof htmlString !== "string") {
    throw new TypeError("Expected htmlString to be a string.");
  }

  container.insertAdjacentHTML("beforeend", htmlString);
}

// Example usage:
const feedDiv = document.querySelector("#activity-feed");
appendHtmlSnippet(feedDiv, '<div class="entry"><strong>Build passed</strong><span> just now</span></div>');
  • Choose the right insertAdjacentHTML() position: Use "beforeend" to append inside the end of the <div>, or "afterbegin" to prepend inside the start.
  • Never pass unsanitized user HTML to insertAdjacentHTML(): Untrusted strings containing <img onerror=...> or <script> can execute arbitrary scripts; sanitize first or create DOM elements directly.

3. Building DOM Nodes Programmatically (Best for Dynamic Data)

For structured content backed by data (such as labels, badges, or list items), constructing elements with document.createElement() and setting .textContent combines clean structure, full DOM references, and XSS safety without parsing HTML strings:

// Build a structured child element cleanly and append it to the <div>
function appendBadgeRow(container, labelText, badgeText) {
  if (!(container instanceof Element)) {
    throw new TypeError("Expected container to be a DOM Element.");
  }

  const row = document.createElement("div");
  row.className = "item-row";

  const label = document.createElement("span");
  label.className = "item-label";
  label.textContent = String(labelText ?? "");

  const badge = document.createElement("span");
  badge.className = "item-badge";
  badge.textContent = String(badgeText ?? "");

  row.append(label, " ", badge);
  container.append(row);

  return row;
}

// Example usage:
const listDiv = document.querySelector("#items-container");
appendBadgeRow(listDiv, "Cache TTL", "300s");
  • Direct element access: Creating nodes with document.createElement() lets you attach listeners, data attributes, or classes immediately without querying the DOM afterward.
  • Safe by construction: Assigning .textContent keeps dynamic values strictly as text even when data comes from external APIs or user forms.