How to manipulate the DOM with JavaScript

· Category: JavaScript

Short answer

Use createElement, textContent, appendChild, remove, and insertAdjacentHTML to build and modify the DOM tree dynamically without relying on innerHTML for user content.

Steps

  1. Create and append an element: javascript const div = document.createElement("div"); div.textContent = "Safe text"; document.body.appendChild(div);
  2. Remove an element: javascript const el = document.querySelector(".old"); el.remove();
  3. Insert HTML at a specific position: javascript const list = document.querySelector("ul"); list.insertAdjacentHTML("beforeend", "<li>New item</li>");
  4. Modify attributes and classes: javascript el.setAttribute("aria-hidden", "true"); el.classList.add("hidden");

Tips

  • Prefer textContent over innerHTML when inserting plain text to avoid XSS.
  • Use DocumentFragment to batch multiple insertions and minimize reflows.

Common issues

  • Using innerHTML with unsanitized user input creates security vulnerabilities.
  • Modifying the DOM inside a loop causes excessive reflow; batch changes with a fragment.