1. Introduction
DOM manipulation is the act of using JavaScript to select elements from the page and change their content, attributes, styles, or structure. This is the foundation of interactive web pages — everything from toggling a menu to rendering a dynamic list relies on DOM manipulation APIs.
Cricket analogy: Just as a ground staff crew changes the pitch cover, boundary rope, or scoreboard mid-match without stopping play, DOM manipulation lets JavaScript select elements and change their content, attributes, or structure while the page keeps running.
The main tasks are: selecting elements, reading or updating their properties/content, creating new elements, and inserting or removing nodes from the tree.
Cricket analogy: Selecting the scoreboard element, reading the current score, updating it after a boundary, and inserting a new 'wicket' banner mirrors the four main DOM tasks: selecting, reading/updating, creating, and inserting or removing nodes.
2. Syntax
// Selecting elements
document.getElementById('myId'); // single Element or null
document.getElementsByClassName('myClass'); // live HTMLCollection
document.getElementsByTagName('li'); // live HTMLCollection
document.querySelector('.myClass'); // first match, static
document.querySelectorAll('.myClass'); // static NodeList of all matches
// Modifying content/attributes
el.textContent = 'New text';
el.innerHTML = '<strong>Bold</strong>';
el.setAttribute('data-id', '42');
el.classList.add('active');
el.style.color = 'red';
// Creating and inserting
const li = document.createElement('li');
li.textContent = 'New item';
parentUl.appendChild(li);
parentUl.insertBefore(li, parentUl.firstChild);
// Removing
li.remove();
parentUl.removeChild(li);3. Explanation
getElementById returns a single element (or null) matched by its unique id — it is the fastest lookup. getElementsByClassName and getElementsByTagName return a live HTMLCollection: a collection that automatically updates if matching elements are added or removed from the DOM afterward.
Cricket analogy: Looking up a player by their unique jersey number in a database is instant and unambiguous, like getElementById, whereas getElementsByClassName('bowler') returns a live list that updates automatically as bowlers are substituted mid-innings.
querySelector and querySelectorAll accept full CSS selector syntax (e.g. '.card > p:first-child') and are far more flexible. querySelectorAll returns a static NodeList — a snapshot taken at call time that does NOT update automatically if the DOM changes later, unlike a live HTMLCollection.
Cricket analogy: A complex query like 'first fielder in the slip cordon' works like querySelector('.slips > .fielder:first-child'), but the resulting list is a frozen snapshot of that moment — it won't update if a fielder is repositioned afterward, unlike a live list.
For inserting text, textContent sets plain text safely (escaping any markup), while innerHTML parses and inserts HTML markup — useful for injecting structured content but risky with untrusted input due to XSS.
Cricket analogy: Announcing a player's name over the PA is safe plain text like textContent, but pasting an unverified fan-submitted banner onto the big screen as raw markup is like innerHTML — flexible but risky if the input isn't trusted.
Gotcha: getElementsByClassName/getElementsByTagName return a LIVE HTMLCollection — iterating it while adding/removing matching elements inside the loop can skip items or cause infinite loops. querySelectorAll returns a STATIC NodeList, which is safer to iterate while mutating the DOM. Also, never assign untrusted/user-supplied strings to innerHTML — it can execute injected scripts (XSS).
4. Example
<ul id="list">
<li class="item">Apples</li>
<li class="item">Bananas</li>
</ul>const liveItems = document.getElementsByClassName('item'); // live HTMLCollection
const staticItems = document.querySelectorAll('.item'); // static NodeList
console.log(liveItems.length); // 2
console.log(staticItems.length); // 2
const ul = document.getElementById('list');
const newLi = document.createElement('li');
newLi.className = 'item';
newLi.textContent = 'Cherries';
ul.appendChild(newLi);
console.log(liveItems.length); // updates automatically
console.log(staticItems.length); // does NOT update -- stale snapshot5. Output
Console output:
2 // liveItems.length before appendChild
2 // staticItems.length before appendChild
3 // liveItems.length AFTER appendChild (auto-updated, live collection)
2 // staticItems.length AFTER appendChild (unchanged, static snapshot)
Resulting DOM:
<ul id="list">
<li class="item">Apples</li>
<li class="item">Bananas</li>
<li class="item">Cherries</li>
</ul>6. Key Takeaways
- getElementById returns one element; getElementsByClassName/TagName return a live HTMLCollection.
- querySelector/querySelectorAll accept CSS selectors; querySelectorAll returns a static NodeList.
- Live collections auto-update on DOM changes; static NodeLists are frozen snapshots.
- Use textContent for plain text (safe); avoid innerHTML with untrusted input (XSS risk).
- createElement + appendChild/insertBefore is the standard pattern for inserting new nodes.
- remove() and removeChild() both delete nodes from the tree.
Practice what you learned
1. Which selection method returns a live HTMLCollection that auto-updates when matching elements are added?
2. What does querySelectorAll('.item') return?
3. Why is assigning untrusted user input directly to innerHTML risky?
4. If you iterate a live HTMLCollection while adding matching elements inside the loop, what can happen?
5. Which method sets an element's text content while automatically escaping any HTML-like characters?
Was this page helpful?
You May Also Like
The DOM in JavaScript
Understand the Document Object Model — the live, tree-structured in-memory representation of a web page that JavaScript reads and modifies.
Event Handling in JavaScript
Learn how to listen for and respond to user interactions and browser events using addEventListener and the event object.
Form Validation in JavaScript
Learn to validate form input using built-in HTML5 constraint validation attributes and custom JavaScript logic.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics