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
- Create and append an element:
javascript const div = document.createElement("div"); div.textContent = "Safe text"; document.body.appendChild(div); - Remove an element:
javascript const el = document.querySelector(".old"); el.remove(); - Insert HTML at a specific position:
javascript const list = document.querySelector("ul"); list.insertAdjacentHTML("beforeend", "<li>New item</li>"); - Modify attributes and classes:
javascript el.setAttribute("aria-hidden", "true"); el.classList.add("hidden");
Tips
- Prefer
textContentoverinnerHTMLwhen inserting plain text to avoid XSS. - Use
DocumentFragmentto batch multiple insertions and minimize reflows.
Common issues
- Using
innerHTMLwith unsanitized user input creates security vulnerabilities. - Modifying the DOM inside a loop causes excessive reflow; batch changes with a fragment.