Lesson 3.8: JavaScript and the DOM
JavaScript & the DOM
HTML builds it. CSS styles it. JavaScript brings it to life. Learn how to grab any element on your page and change it in real time — the moment a user clicks a button.
Lesson Objectives
- Explain what JavaScript is and how it fits alongside HTML and CSS
- Describe what the DOM (Document Object Model) is and how the browser creates it
- Use
document.getElementById()andquerySelector()to select elements - Change element content using
innerHTMLandtextContent - Change element styles using
element.style - Add and remove CSS classes using
classList.add(),classList.remove(), andclassList.toggle() - Respond to user clicks using
addEventListener
Part 1: What Is JavaScript?
You've used HTML to build the structure of your page and CSS to style it. But if you want something to happen — text that changes, a button that responds, a section that appears or disappears — you need JavaScript.
JavaScript is the programming language of the web. It runs directly in the browser — no installation needed. It makes your website interactive and dynamic, meaning things can change while the user is still on the page, without reloading.
Real-World JavaScript in Action
- 🛒 Online store — click "Add to Cart" and the cart total updates instantly
- 💬 Streaming site — click a thumbnail and a description appears below it
- 🔍 Search box — as you type, live suggestions appear and filter in real time
- 📝 Contact form — JavaScript checks fields are valid before the form submits
- 🌙 Dark mode toggle — a single click switches the entire page's color scheme
Where Does JavaScript Go?
JavaScript is written inside a <script> tag, placed at the bottom of the HTML body — just before </body>. This ensures the HTML loads fully before JavaScript tries to find and modify elements.
null and your code breaks. Placing <script> at the bottom of <body> guarantees all elements exist first.
Part 2: What Is the DOM?
When your browser loads an HTML file, it doesn't just display the page — it builds a live, interactive map of every element. This map is called the DOM (Document Object Model).
Think of the DOM as a tree of objects. Every HTML tag becomes a node in the tree. JavaScript can find any node, read its content, change it, add new ones, or remove them — all without refreshing the page.
DOM Tree Visualized
Every node in this tree is an object JavaScript can access. The document object is the root — the entry point for all DOM operations.
Part 3: Selecting Elements
Before JavaScript can change anything on the page, it needs to find the element. There are two main ways to do this:
| Method | Selects By | Returns | Best For |
|---|---|---|---|
getElementById('id') | ID attribute | One element (or null) | Finding a specific, unique element quickly |
querySelector('selector') | Any CSS selector | First matching element | Flexible selection by tag, class, ID, or combo |
querySelectorAll('selector') | Any CSS selector | All matching elements (NodeList) | Looping over multiple elements |
Part 4: Changing the DOM
Once you've selected an element, you can change it in several ways. Here are the most important DOM manipulation techniques:
el.innerHTML = "New text"
el.style.color = "blue"
el.classList.add("active")
el.classList.toggle("dark")
el.style.display = "none"
el.setAttribute("src","new.jpg")
innerHTML vs. textContent
Responding to Clicks with addEventListener
The preferred way to attach a click handler in modern JavaScript is addEventListener. It keeps your JavaScript separate from your HTML — no onclick="" attributes needed in the HTML:
Using classList.toggle for Dark Mode
<script> tag is in the <head> and you call document.getElementById('greeting'), the element doesn't exist yet — you'll get null and an error. Always place scripts at the bottom of <body>.
Part 5: See It in Action
Both demos below are powered entirely by JavaScript and the DOM — no page reloads, no server. Try every button and observe the changes in real time.
Welcome to my webpage!
Each button runs a different DOM method — watch the heading and box react instantly.
A counter built with innerHTML, a variable, and addEventListener:
0
Each button reads and updates a count variable, then writes the new value to the DOM with innerHTML.
Student Activity
Make Your Page Interactive with JavaScript
Title: Make Your Page Interactive with JavaScript | Platform: Knowledge Pillars Coding Lab
You've built and styled your personal site across Units 1–2 and added advanced CSS in Unit 3. Now give it a brain — add JavaScript that responds to user clicks and changes content live.
-
Add an interactive greeting section to
index.html. Place this inside your<main>element:<section id="interactive-greeting"> <h2 id="greeting">Welcome to my webpage!</h2> <button id="changeBtn" type="button">Click to Update Message</button> </section>💾 Save
index.html. -
Add your JavaScript just before
</body>. This usesaddEventListenerto respond to the button click:<script> let btn = document.getElementById('changeBtn'); let greeting = document.getElementById('greeting'); btn.addEventListener('click', function() { greeting.innerHTML = 'Thanks for visiting my site!'; greeting.style.color = '#0a2463'; }); </script>💾 Save and refresh — click the button and watch the heading change!
-
Add a dark mode toggle. First add this CSS to
style.css, then add the HTML button and JavaScript toindex.html:/* In style.css */ .darkmode { background-color: #1a1a2e; color: #f0f0f0; }<!-- In index.html — add this button somewhere visible --> <button id="darkBtn" type="button">Toggle Dark Mode</button> <!-- In your <script> block --> document.getElementById('darkBtn').addEventListener('click', function() { document.body.classList.toggle('darkmode'); });💾 Save both files. Click your dark mode button — the whole page should switch!
-
Build a click counter. This demonstrates reading a variable, updating it, and writing it back to the DOM:<!-- In index.html --> <p id="count-display">0</p> <button id="countBtn" type="button">Click Me!</button> <!-- In your <script> block --> let count = 0; document.getElementById('countBtn').addEventListener('click', function() { count = count + 1; document.getElementById('count-display').innerHTML = count; });
💾 Save and commit your changes in the Knowledge Pillars Coding Lab.
🌟 Bonus Challenges
Random quote generator using an array:
Change multiple style properties at once:
Vocabulary
id attributegetElementByIdLesson Summary
| Method / Property | What It Does |
|---|---|
<script> at bottom of <body> | Ensures all HTML elements exist before JavaScript tries to find them |
document.getElementById('id') | Finds the element with the matching id and returns it as an object |
document.querySelector('selector') | Finds the first element matching any CSS selector |
element.innerHTML = "..." | Replaces the content inside an element — can include HTML tags |
element.textContent = "..." | Replaces content with plain text only — no tags rendered |
element.style.color = "blue" | Changes a CSS property directly on the element via JavaScript |
element.classList.add('class') | Adds a CSS class to the element |
element.classList.toggle('class') | Adds the class if absent; removes it if present — for on/off toggles |
element.addEventListener('click', fn) | Runs a function when the element is clicked — the modern event handling approach |
| DOM ≠ HTML source | The DOM is live — JS changes are instant on screen but don't modify the saved HTML file |
Knowledge Check
Read each question carefully and select the best answer. Each question has one correct response.
1. What does document.getElementById('greeting') return?
2. Why should a <script> tag be placed at the bottom of <body> rather than in the <head>?
3. What is the difference between innerHTML and textContent?
4. What does element.classList.toggle('darkmode') do?
5. What is the DOM, and is it the same as the HTML source file?
