Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript DOM Manipulation: Selecting, Updating, Rendering

DOM manipulation lets JavaScript update page structure, styles, and content dynamically.

Why this matters

Interactive websites rely on DOM operations for input handling, validation messages, and real-time UI updates.

Selecting Elements Safely

Use querySelector for single element and querySelectorAll for NodeList collections.

Check for null before manipulating selected elements to prevent runtime errors.

Prefer semantic selectors and data attributes for robust targeting.

Updating Content and Classes

Use textContent for plain text insertion and innerHTML only when trusted HTML is intended.

ClassList API (add/remove/toggle/contains) is cleaner than manual className concatenation.

Batch updates when possible to reduce layout thrashing in complex UI updates.

Code Examples

Query and Content Update

const heading = document.querySelector("#title");
if (heading) {
  heading.textContent = "Updated from JavaScript";
}

textContent is safe for plain text updates.

Class Toggle for Theme

const btn = document.querySelector("#toggleBtn");
btn?.addEventListener("click", () => {
  document.body.classList.toggle("dark");
});

classList toggle is a common and clean UI pattern.

Render Dynamic List

const list = document.querySelector("#skills");
const data = ["HTML", "CSS", "JavaScript"];
if (list) {
  list.innerHTML = data.map((item) => `<li>${item}</li>`).join("");
}

Quick rendering pattern for small static-safe content.

Common Mistakes and Fixes

Using innerHTML with untrusted data

Use textContent or sanitize inputs before HTML injection.

Not checking element existence

Guard with null checks or optional chaining before mutation.

Frequent style writes in loops

Batch changes with classes and minimal repaint triggers.

Frequently Asked Questions

querySelector or getElementById?

Both are fine. querySelector is flexible with CSS selectors; getElementById is specific and simple for ID lookups.

Is innerHTML always bad?

No, but unsafe with untrusted input due to XSS risk.

How to improve DOM update performance?

Minimize frequent reflows, batch updates, and use classes instead of inline style changes.

Should I use framework or vanilla DOM?

For learning and small tools, vanilla is great. Larger apps often benefit from framework abstractions.

Related JavaScript Topics