100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
JavaScript

DOM Manipulation in JavaScript

Learn how to select, create, modify, and remove DOM elements using JavaScript, and the key differences between the main selector APIs.

DOM & EventsBeginner10 min readJul 8, 2026
Analogies

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

javascript
// 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

html
<ul id="list">
  <li class="item">Apples</li>
  <li class="item">Bananas</li>
</ul>
javascript
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 snapshot

5. Output

text
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

Was this page helpful?

Topics covered

#JavaScript#JavaScriptProgrammingStudyNotes#Programming#DOMManipulationInJavaScript#DOM#Manipulation#Syntax#Explanation#WebDevelopment#StudyNotes#SkillVeris