🌐 JavaScript DOM Manipulation — Select, Modify & Create Elements
Learn JavaScript DOM manipulation — querySelector, classList, createElement, innerHTML vs textContent, and performance tips. Practical examples and interview Q&A inside.
The DOM (Document Object Model) is a tree of nodes representing your HTML. JavaScript can read it, change it, and respond to it.
🔎 Selecting elements
document.querySelector('.btn')— first matchdocument.querySelectorAll('.item')— all matches (static NodeList)document.getElementById('hero')— by id, fastest
✍️ Modifying
el.textContent = 'Hi'— safe, plain textel.innerHTML = '<b>Hi</b>'— parses HTML (XSS risk!)el.classList.add/remove/toggle('active')el.setAttribute('href', '/x')el.style.color = 'red'
🌱 Creating
const li = document.createElement('li');
li.textContent = 'New item';
document.querySelector('ul').append(li);⚡ Performance tip
Avoid touching the DOM in a tight loop. Build a DocumentFragment or HTML string once, then insert it.
💻 Code Examples
Toggle a class on click
document.querySelector('#menu-btn')
.addEventListener('click', () => {
document.body.classList.toggle('menu-open');
});Output:
Body gets/loses the 'menu-open' class on each click.
Render a list
const items = ['Apple', 'Banana', 'Cherry'];
const ul = document.querySelector('#fruits');
ul.innerHTML = items
.map(f => `<li>${f}</li>`)
.join('');Output:
<li>Apple</li><li>Banana</li><li>Cherry</li>
⚠️ Common Mistakes
- Using innerHTML with user input — opens XSS. Use textContent or sanitize first.
- Querying inside loops — cache the element once: `const list = document.querySelector('#list')`.
- Confusing NodeList with Array — NodeList has forEach but not map/filter. Use `[...nodeList]` or `Array.from()` to convert.
- Forgetting that querySelectorAll returns a STATIC list — it doesn't auto-update when the DOM changes.
🎯 Interview Questions
Real questions asked at top product and service-based companies.
Q1.What is the DOM?Beginner
The Document Object Model — a tree-shaped, in-memory representation of an HTML document. JavaScript uses it to read and modify the page.
Q2.What's the difference between innerHTML and textContent?Beginner
innerHTML parses the string as HTML — `<b>hi</b>` becomes bold. textContent treats it as plain text. Always prefer textContent for user input to avoid XSS.
Q3.Difference between querySelector and getElementById?Intermediate
getElementById is ID-only and slightly faster. querySelector accepts any CSS selector. Use getElementById when you have an ID; querySelector for everything else.
Q4.What's a DocumentFragment and why use it?Intermediate
An off-screen DOM container. Appending nodes to a fragment doesn't trigger reflows. When you finally append the fragment to the page, all children are inserted in a single operation — big performance win for batch inserts.
Q5.How would you detect when an element enters the viewport?Advanced
Use IntersectionObserver — fires a callback when the element's visibility crosses a threshold. Far more efficient than scroll-event polling.
🧠 Quick Summary
- querySelector(All) for modern selection; getElementById for speed.
- textContent is safe; innerHTML can be XSS-prone.
- Use classList for class changes — cleaner than className.
- Batch DOM writes with DocumentFragment.
- IntersectionObserver beats scroll listeners for visibility detection.