Lesson 1, Topic 1
In Progress

Lesson 3.8: JavaScript and the DOM

Lesson 3.8 – JavaScript & the DOM | Knowledge Pillars HCCS
Unit 3 · Lesson 3.8

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.

HTML & CSS Web Design ~55 Minutes Intermediate

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() and querySelector() to select elements
  • Change element content using innerHTML and textContent
  • Change element styles using element.style
  • Add and remove CSS classes using classList.add(), classList.remove(), and classList.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.

<body> <!-- all your HTML content here --> <!-- JavaScript goes at the bottom of body --> <script> // Your JavaScript code here console.log('Page loaded!'); </script> </body>
💡 Why at the bottom? JavaScript runs line by line as the browser reads it. If a script tries to find an element before that element has loaded in the HTML, it returns 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.

💡 DOM ≠ HTML source code. The DOM is a live, in-memory representation of the page as it currently exists. When JavaScript changes the DOM — adding text, hiding a section — the change is instant on screen, but the original HTML file on disk is unchanged. Refresh the page and the original HTML reloads.

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 1: by ID — finds the one element with that exact id let greeting = document.getElementById('greeting'); // Method 2: querySelector — uses CSS selector syntax (more flexible) let heading = document.querySelector('h2'); // first h2 let myBtn = document.querySelector('#changeBtn'); // by ID let firstBox = document.querySelector('.box'); // by class // querySelectorAll — returns ALL matching elements as a list let allBoxes = document.querySelectorAll('.box');
Selecting Elements — Methods Compared
Method Selects By Returns Best For
getElementById('id')ID attributeOne element (or null)Finding a specific, unique element quickly
querySelector('selector')Any CSS selectorFirst matching elementFlexible selection by tag, class, ID, or combo
querySelectorAll('selector')Any CSS selectorAll 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:

Change Text Content
el.innerHTML = "New text"
Change a Style
el.style.color = "blue"
Add a CSS Class
el.classList.add("active")
Toggle a Class
el.classList.toggle("dark")
Hide an Element
el.style.display = "none"
Change an Attribute
el.setAttribute("src","new.jpg")

innerHTML vs. textContent

// innerHTML — can include HTML tags (renders them) document.getElementById('greeting').innerHTML = 'Hello, <strong>world</strong>!'; // Result: Hello, <strong>world</strong> renders as bold // textContent — plain text only (safer, no HTML injection) document.getElementById('greeting').textContent = 'Hello, world!'; // Result: literal plain text — no tags rendered

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:

// Step 1: Select the elements let btn = document.getElementById('changeBtn'); let greeting = document.getElementById('greeting'); // Step 2: Add an event listener — "when btn is clicked, run this function" btn.addEventListener('click', function() { greeting.innerHTML = 'Thanks for visiting my site!'; greeting.style.color = '#0a2463'; });

Using classList.toggle for Dark Mode

/* In style.css */ .darkmode { background-color: #1a1a2e; color: #fff; } // In your <script> — toggle dark mode on button click document.getElementById('darkBtn').addEventListener('click', function() { document.body.classList.toggle('darkmode'); }); // First click: adds .darkmode to <body> → dark mode ON // Second click: removes .darkmode → dark mode OFF // Third click: adds it back again → and so on!
⚠️ Common mistake — script placed in <head>: If your <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.

🔍 Live Demo 1 — DOM Manipulation

Welcome to my webpage!

📦 I respond to classList.toggle()

Each button runs a different DOM method — watch the heading and box react instantly.

🔍 Live Demo 2 — Click Counter

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

🛠️ Code It

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.

  1. 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.

  2. Add your JavaScript just before </body>. This uses addEventListener to 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!

  3. Add a dark mode toggle. First add this CSS to style.css, then add the HTML button and JavaScript to index.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!

  4. 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:

let quotes = ["You're awesome!", "Keep coding!", "JavaScript rocks!"]; document.getElementById('quoteBtn').addEventListener('click', function() { let i = Math.floor(Math.random() * quotes.length); document.getElementById('quote-display').innerHTML = quotes[i]; });

Change multiple style properties at once:

let el = document.getElementById('greeting'); el.style.backgroundColor = '#f5c400'; el.style.padding = '10px 16px'; el.style.borderRadius = '8px';

Vocabulary

JavaScript
The programming language of the web — runs in the browser and makes pages interactive and dynamic
DOM
Document Object Model — the browser's live, in-memory map of every HTML element on the page
getElementById()
Finds and returns the one element with the matching id attribute
querySelector()
Finds the first element matching any CSS selector — more flexible than getElementById
innerHTML
A property that gets or sets the HTML content inside an element — can render HTML tags
textContent
Gets or sets the plain text content of an element — does not render HTML tags (safer)
classList.toggle()
Adds a CSS class if it's absent, removes it if it's present — perfect for on/off features like dark mode
addEventListener()
Attaches a function to run when a specific event occurs on an element — the modern, preferred way to handle clicks

Lesson Summary

Lesson 3.8 — Key Concepts
Method / PropertyWhat 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 sourceThe 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?