Lesson 12 / JavaScript

JavaScript in the DOM

Time
55 min
Type
Reading + Interactive
Level
Intermediate

Use JavaScript and the Document Object Model to select elements, change content, respond to events, and create dynamic interfaces.

Teacher Notes / In-Class Use

Demo Live

  • Use the DOM lab to show select, change, listen, and respond as the core JavaScript pattern.
  • Compare textContent, classList, setAttribute, and appendChild as different kinds of DOM changes.

Try In Class

  • Have students create a button that toggles a class on one visible element.
  • Ask students to write one console.log before changing the DOM so they can confirm the event fired.

Submit Or Check

  • The interaction should still work after refresh and should not require inline onclick attributes.
  • Students should be able to point to the selected element, the event listener, and the changed class or content.

Watch For

  • Scripts running before the HTML exists because the script is loaded too early.
  • Students changing inline styles directly when toggling a class would be clearer.

Learning Goals

  • Explain the DOM as a living representation of an HTML document
  • Modify DOM element content, attributes, styles, and classes
  • Use event listeners and the event object to respond to user actions

Interactive Demo

How to use this demo.

Use the demo as a small lab. Change one thing, observe the result, then connect it back to your own project.

What To Try

  • Click each action button and watch the preview and code sample update.
  • Reset the demo, then predict what will change before pressing the next button.

What Changes

  • Text, classes, attributes, and list items update through JavaScript.
  • The code sample shows the DOM method behind each interaction.

What To Notice

  • Most interactions follow the pattern: select something, listen for an event, change something.
  • Changing classes is usually cleaner than writing many inline styles from JavaScript.

Apply It

  • Add one button to your project that toggles a class on a visible element.

Interactive Demo

DOM Interaction Lab

Use the controls to change content, classes, attributes, and elements in the preview. The code updates to show the JavaScript behind the action.

Ready

Original card title

JavaScript can select this text and update it after the page loads.

Visit LSU
  • Existing list item
const title = document.querySelector('[data-dom-title]');
title.textContent = 'Updated by JavaScript';

What to notice

  • JavaScript selects elements before it changes them.
  • classList changes styling without rewriting the HTML.
  • createElement and appendChild add new content to the page.

Try this

  • Click each action and read the generated code.
  • Reset the demo, then predict what each action will change.
  • Rebuild one action in your own script.js file.

This demo uses extra JavaScript for teaching. The code sample shows the pattern to practice. View full demo source (opens in a new tab).

Introduction

As front-end developers, we're not just concerned with static web pages. We want to create interactive and dynamic experiences that respond to user actions and provide engaging feedback.

That's where JavaScript and the Document Object Model, or DOM, come in. Think of the DOM as a living, breathing representation of your HTML document.

JavaScript allows you to access and manipulate this DOM, changing the content, structure, and style of your web page in real time.

In this chapter, we'll learn how to select and manipulate DOM elements, respond to user events, and create dynamic effects that bring your web pages to life.

Adding JavaScript to Your Web Page

You can include JavaScript in your HTML document in three ways.

Inline

JavaScript code can be embedded directly in an HTML element using an event attribute like onclick.

<button onclick="alert('Hello!')">Click me</button>

Internal

JavaScript can be written inside script tags in the HTML file itself.

<head>
  <script>
    // Your JavaScript code here
  </script>
</head>

External

JavaScript can be placed in a separate file and linked with the src attribute.

This last approach is preferred for better organization and maintainability.

<body>
  ...
  <script src="script.js"></script>
</body>

The DOM: Your Webpage's Blueprint

The DOM is a tree-like structure that represents all elements, attributes, and text in your HTML. Each element becomes a node, and JavaScript can interact with these nodes.

Modifying DOM Elements

Once you've selected an element, you can modify its content, attributes, or style using JavaScript.

Modifying Content

element.textContent = 'New content'; // Updates the text content
element.innerHTML = '<p>New HTML content</p>'; // Updates the HTML content

Modifying Attributes

element.setAttribute('class', 'newClass');
element.href = 'https://www.example.com';

Modifying Styles

element.style.color = 'red';
element.style.display = 'none';

Working with classList

The classList API provides a more convenient way to work with an element's classes.

  • add(className): Adds a class to the element.
  • remove(className): Removes a class from the element.
  • toggle(className): Toggles a class on or off.
  • contains(className): Checks if the element has a specific class.
<div class="my-class">Element content</div>

const element = document.querySelector('.my-class');
element.classList.add('active');

if (element.classList.contains('active')) {
  // Do something
}

Traversing the DOM

Being able to traverse the DOM is useful when you need to move between related elements. You can navigate the DOM tree using these properties.

  • parentNode: The parent of the element.
  • childNodes: A collection of the element's child nodes.
  • firstChild: The element's first child node.
  • lastChild: The element's last child node.
  • nextSibling: The next sibling of the element.
  • previousSibling: The previous sibling of the element.
<div id="parent">
  <div id="child">First child</div>
  <div>Second child</div>
</div>

const child = document.getElementById('child');
const parent = child.parentNode;
const nextSibling = child.nextSibling;

Creating and Inserting Elements

JavaScript allows you to dynamically create new elements and insert them into the DOM.

const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';

const parent = document.getElementById('parent');
parent.appendChild(newParagraph);

Event Listeners: Responding to User Actions

Event listeners allow you to execute JavaScript code when a specific event occurs on an element, such as a click, hover, or form submission.

element.addEventListener('click', () => {
  // Code to execute when the element is clicked
});

Using the Event Object

When an event occurs, an event object is passed to the event listener callback function. It contains information such as the event target, type, and methods like preventDefault().

<a id="myLink" href="https://www.lsu.edu/">Link to LSU</a>

const link = document.getElementById('myLink');

link.addEventListener('click', (event) => {
  event.preventDefault();
  // Custom code here
});

Creating a Navigation Menu Toggle (Revisited)

This example revisits the use of DOM manipulation to control visibility of a navigation menu using JavaScript, often used in mobile layouts.

Off-Canvas Menu

This pattern shows a navigation menu that slides in from the side, typically used on mobile devices.

Additional Resources

classList API - MDN | Events Documentation - MDN

Checkpoint

Before moving on, make sure these feel true.

  • I can select an element from the DOM.
  • I can respond to a user event with addEventListener.
  • I can change content, classes, or attributes without using inline JavaScript.

Project Connection

This lesson supports current class projects.

Practice

  • Create a button that toggles a menu class.
  • Update text on the page after a click.