Topic 35 of 59 JavaScript Asynchronous & Advanced Concepts Interactive Tutorial

JavaScript DOM Fundamentals: Selecting and Changing Web Page Elements

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is JavaScript DOM Fundamentals? Core Concept & Direct Summary

Core Objective & Problem Statement

How do you select and manipulate DOM elements in JavaScript?

Direct Answer Summary
Select elements using querySelector/querySelectorAll or getElementById; modify attributes, textContent, innerHTML, or classList.

Everything you've learned so far — variables, loops, functions, events — has one limitation:the results only appeared in the console.Your users never see the console. They see thepage.

Today that changes. Today your JavaScript reaches out and touches the actual web page — changing text, swapping styles, updating content live, right before the user's eyes. 👀

when your first program changed a paragraph's text with one magical line?

script.js
Run Online
document.getElementById("message").textContent = "Hello! 🚀";

That magic has a name: theDOM. In this lesson, you'll understand what the DOM actually is, master every way tofindelements, and learn the safe, correct ways tochangethem. This is the lesson where JavaScript becomes visible. Let's light it up. 💡

How Does JavaScript DOM Fundamentals Work? In-Depth Mechanics & Architecture

textContent sets plain text safely (prevents XSS); innerHTML parses HTML tags. Element creation uses document.createElement().

What Is the DOM? The Family Tree of Your Page 🌳

DOM = Document Object Model— the browser's live, JavaScript-accessible representation of your HTML page.

When the browser loads your HTML, it doesn't just display it — it builds atree of objectsin memory:

script.js
Run Online
<body>
  <h1>My Shop</h1>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
  </ul>
</body>

Becomes this tree:

Architecture Diagram
document└── body    ├── h1  ────── "My Shop"    └── ul        ├── li ──── "Apples"        └── li ──── "Bananas"

Every HTML element becomes a JavaScriptobject— with properties you can read and change. Change the object, and the page updatesinstantly. No reload. That's the entire secret of interactive websites:

HTML is the blueprint. The DOM is the living building. JavaScript renovates it while people are inside.🏗️

And the gateway to it all is one global object:document.


Part 1: SELECTING Elements — Finding Your Targets 🎯

Before you can change anything, you mustfindit. JavaScript gives you several selector tools — here's each one, then the only two you really need.

① getElementById() — The Classic

Finds theoneelement with a givenid(ids are unique per page):

script.js
Run Online
<h1 id="pageTitle">Welcome!</h1>
<script>  const title = document.getElementById("pageTitle");  console.log(title.textContent);   // "Welcome!"</script>

② querySelector() — The Modern Superstar ⭐

Finds thefirstelement matchingany CSS selector— ids, classes, tags, anything:

script.js
Run Online
document.querySelector("#pageTitle");
// by id (note the #)document.querySelector(".product-card");     // by class (note the .)document.querySelector("p");                 // by tagdocument.querySelector("ul li:first-child"); // any CSS selector works!document.querySelector("form input[type='email']");  // even complex ones!

If you know CSS selectors, you already know querySelector.Same rules, same syntax.

③ querySelectorAll() — Grab Them All

Returnsallmatching elements as a list (a NodeList — array-like):

script.js
Run Online
const items = document.querySelectorAll("li");
for (let item of items) {
  // for…of from Lesson 17! ✅  console.log(item.textContent);}
  // NodeLists even support forEach directly:items.forEach(item => console.log(item.textContent));

The Older Relatives (Know Them, Rarely Use Them)

script.js
Run Online
document.getElementsByClassName("card");
// live HTMLCollectiondocument.getElementsByTagName("li");       // live HTMLCollection

These returnlivecollections that auto-update when the page changes — sounds handy, but causes subtle bugs, and they lack modern methods. Modern code prefersquerySelectorAll.

🏆 The Selector Decision Table

NeedUse
One element, any selectorquerySelector()⭐
Many elementsquerySelectorAll()⭐
By id (slightly faster, very explicit)getElementById()✅
Old-school live collectionsgetElementsByClassName/TagName(legacy)

⚠️ The Null Trap — Check Before You Touch

A selector that finds nothing returnsnull— and touching null crashes:

script.js
Run Online
const box = document.getElementById("doesNotExist");
console.log(box);
// null
box.textContent = "Hi";
// ❌ TypeError: Cannot read properties of null!

Safe habits:

script.js
Run Online
const box = document.querySelector("#box");
if (box) {
  // truthy check from Lesson 7! ✅  box.textContent = "Hi";}
  // Or optional chaining from Lesson 6:document.querySelector("#box")?.classList.add("active");

And remember Lesson 3's rule:script at the bottom of<body>(or useDOMContentLoadedfrom Lesson 30) — you can't select elements that haven't been parsed yet.


Part 2: CHANGING Content — Text and HTML ✏️

Found your element? Now change what's inside it.

textContent — Safe Plain Text ✅

script.js
Run Online
const title = document.querySelector("#pageTitle");
title.textContent = "Welcome to my shop! 🛍️";

textContentsetspure text. If your string contains HTML, it's displayedas text, not rendered:

script.js
Run Online
title.textContent = "<b>Hello</b>";// Page literally shows: <b>Hello</b> — tags displayed as characters

innerHTML — HTML That Actually Renders ⚠️

script.js
Run Online
title.innerHTML = "<b>Hello</b>
<em>there</em>";// Page shows: **Hello** *there* — bold and italic rendered ✅

Powerful — but with acritical security warning:

🚨 NEVER use innerHTML with user-provided data.If a user submits<script>maliciousCode()</script>and you inject it via innerHTML, their code runs onyourpage — that's anXSS (Cross-Site Scripting)attack, one of the most common web vulnerabilities.

script.js
Run Online
// ❌ NEVER do this:comment.innerHTML = userInput;
// ✅ Always safe:comment.textContent = userInput;

textContent vs innerHTML — The Rule

textContentinnerHTML
Renders HTML tags?❌ No (shows them as text)✅ Yes
Safe with user data?✅ Yes❌Never!
SpeedFasterSlower (parses HTML)
Use forEverything by defaultTrusted, hardcoded HTML only

Default totextContent. Reach forinnerHTMLonly when you genuinely need rendered markup thatyouwrote.

Reading Works Too

script.js
Run Online
console.log(title.textContent);
// reads current textconsole.log(title.innerHTML);     // reads current HTML source

Part 3: CHANGING Styles 🎨

Inline Styles via .style

script.js
Run Online
const box = document.querySelector("#box");
box.style.color = "white";
box.style.backgroundColor = "crimson";
// ⚠️ camelCase, not dashes!box.style.padding = "20px";box.style.borderRadius = "8px";

CSS property names convert to camelCase:background-color→backgroundColor,font-size→fontSize. (The dash would be read as subtraction!)

classList — The Professional Way ⭐

Inline styles get messy fast. Pros define styles in CSSclassesand toggle them withclassList:

script.js
Run Online
/* Your stylesheet: */.highlight {
  background: #fff3cd;
  border: 2px solid orange;
}.hidden {
  display: none;
}.dark-mode {
  background: #1a1a1a;
  color: white;
}
script.js
Run Online
const box = document.querySelector("#box");
box.classList.add("highlight");
// ➕ add a classbox.classList.remove("highlight");     // ➖ remove itbox.classList.toggle("highlight");     // 🔄 flip on/off (returns new state!)box.classList.contains("highlight");   // ❓ true/false check
// Multiple at once:box.classList.add("highlight", "rounded");

The Dark Mode Toggle — 3 Lines 🌙

script.js
Run Online
const toggleBtn = document.querySelector("#themeBtn");
toggleBtn.addEventListener("click",() => {
  document.body.classList.toggle("dark-mode");
  // that's it! 🌙☀️});

Every dark-mode switch on the internet is essentially this. Events (Lesson 30) + classList = instant interactivity.


Part 4: CHANGING Attributes 🏷️

script.js
Run Online
const link = document.querySelector("#myLink");
const image = document.querySelector("#avatar");
const input = document.querySelector("#email");
// Read attributes:
console.log(link.getAttribute("href"));
// Set attributes:
link.setAttribute("href", "https://example.com");
image.setAttribute("src", "new-photo.png");
input.setAttribute("placeholder", "Enter your email");
// Remove attributes:
input.removeAttribute("disabled");

Common direct properties(often simpler than setAttribute):

script.js
Run Online
image.src = "new-photo.png";
// direct property ✅
input.value = "priya@example.com";
// read/write input values
input.disabled = true;
// booleans work directly
link.href = "https://example.com";

🛠️ Mini Project: Live Profile Card Editor 🪪

Everything from this lesson — selecting, content, styles, classes — in one interactive widget:

script.js
Run Online
<div id="card" class="card"> <h2 id="cardName">Your Name</h2> <p id="cardRole">Your Role</p></div><input id="nameInput" placeholder="Type your name…"><button id="themeBtn">🎨 Toggle Theme</button><style> .card {
  padding: 24px;
  border-radius: 12px;
  background: #f0f0f0;
  width: 260px;
} .card.fancy {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}</style><script> const nameInput = document.querySelector("#nameInput");
const cardName = document.querySelector("#cardName");
const card = document.querySelector("#card");
const themeBtn = document.querySelector("#themeBtn");
// Live-typing: input event (Lesson 30!) updates the card instantly:
nameInput.addEventListener("input",(event) => {
  const typed = event.target.value.trim();
  cardName.textContent = typed === "" ? "Your Name" : typed;
  // safe: textContent ✅
});
// Theme toggle with classList:
themeBtn.addEventListener("click",() => {
  card.classList.toggle("fancy");
});
</script>

Type in the box → the card updateswith every keystroke. Click the button → the card flips themes.No reload, no library — just the DOM.You now hold the exact skills behind every live-preview feature on the web. 🏆


Common Beginner Mistakes (And Fixes)

❌ Mistake🔍 What Happens✅ Fix
querySelector("#id")before HTML loadsReturns null → TypeErrorScript before</body>, or DOMContentLoaded
Forgetting#/.in querySelectorquerySelector("card")finds nothingIds need#, classes need.
innerHTMLwith user inputXSS security hole 🚨textContentfor user data — always
box.style.background-colorSyntaxError — dash = subtractioncamelCase:backgroundColor
Touching a null element"Cannot read properties of null"if (el)guard or?.
Styling with .style everywhereUnmanageable inline-style soupDefine CSS classes, toggle with classList
getElementsByClassName()[0]habitsLive-collection surprisesquerySelector(".class")instead

Quick Self-Check: Lesson 35 Quiz 🧠

  1. What is the DOM, in one sentence?
  2. Write the code to select the element<p class="intro">.
  3. Why iselement.innerHTML = userCommentdangerous, and what's the safe alternative?
  4. What's the difference betweenclassList.add(),remove(), andtoggle()?
  5. Fix this:document.querySelector("myTitle").textContent = "Hi";(the id ismyTitle)

(Answers: 1. The browser's live object-tree representation of your HTML page, which JavaScript can read and modify · 2.document.querySelector(".intro")· 3. User input could contain malicious scripts (XSS); useelement.textContent = userComment— it renders text safely without interpreting HTML · 4. add puts a class on, remove takes it off, toggle flips its current state (on→off, off→on) · 5. Missing the id marker:querySelector("#myTitle")— without # it searches for atag)

JavaScript Decision Matrix & Syntax Comparison

Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (initialized as undefined)Hoisted (Temporal Dead Zone - ReferenceError)Hoisted (Temporal Dead Zone - ReferenceError)
Reassignable✓ Yes✓ Yes✗ No (Immutable binding)
Redeclarable in Same Scope✓ Yes (Error-prone)✗ No (SyntaxError)✗ No (SyntaxError)
Window Object BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, process, globalThis
DOM & UI Manipulation✓ Full access (document.querySelector)✗ No DOM (Headless / Non-UI)
File System & OS Access✗ Blocked (Sandboxed security)✓ Full access (fs, os, child_process)
Primary FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
const btn = document.querySelector('.submit-btn');
btn.textContent = 'Processing...';
btn.classList.add('active');
const newDiv = document.createElement('div');
newDiv.innerHTML = '<p>Inserted dynamically</p>';
document.body.appendChild(newDiv);

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked questions for frontend & full-stack roles
Q

Q: What is the difference between innerHTML and textContent?

A: textContent retrieves/sets raw text node values without parsing HTML tags (safe against XSS); innerHTML parses string contents as HTML markup.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations