Week 4: DOM Manipulation
To Do This Week:
Assignments:
Read (Optional!): Chapters from Eloquent JavaScript:
Upcoming Assignments
- Clickable Page (5%) — no AI-generated code (Due Week 6 — 9/30)
Module Notes
This week we move from working with data (arrays, iterators) to working with the page itself. The DOM (Document Object Model) is the browser's live, tree-shaped representation of your HTML and it elements or nodes. JavaScript can reach into that tree to select elements, read and change them, add or remove them, and respond to what the user does.
The whole process for the Clickable Page is: select an element → listen for a click → change something on the page. Below are some possible changes with click events.
Setting up VS Code for this class
VS Code can help you format your code, but it should not write code for you. These steps turn off suggested completions and keep the formatting help on.
- Open Settings: Cmd + , on Mac, or Ctrl + , on Windows.
- In the search bar at the top, type
disable AI features. Check the box for Chat: Disable AI Features. - Search
inline suggest. Uncheck Editor › Inline Suggest: Enabled. - Search
quick suggestions. Set Other, Comments, and Strings all to off. - Search
suggest on trigger. Uncheck Editor: Suggest On Trigger Characters. - Search
auto closing tags. Make sure HTML: Auto Closing Tags is checked. - Search
format on save. Check Editor: Format On Save. - Search
linked editing. Check Editor: Linked Editing.
In-class Exercises
Open each file in the browser and in your code editor.
1. DOM Playground: Buttons, Boxes & Menus
Six small demos. Each one uses a button to change one thing. The only CSS in the file is the CSS that JavaScript changes.
2. Clickable Page Template (empty starter)
A blank starter page to build your project on. It has no JavaScript and no animation. Every element you might click or change already has an id.
3. Clickable Page Demo (the same template, with changes)
The template with one change attached to each clickable element. Compare it with the empty starter.
1. Selecting Elements
-
document.getElementById("box")
Selects one element by its ID. No#. -
document.querySelector(".card")
Selects the first element that matches a CSS selector:".card"for a class,"#box"for an id,"main"for a tag. -
document.body
The<body>is already selected for you. -
document.querySelectorAll(".card")
Selects all matching elements. -
document.getElementsByClassName("card")
Selects all elements with a class name.
Best Practice: Store your selection in a variable so you don't re-select every time.
const box = document.getElementById("box");
2. Changing Content
-
element.textContent = "New text"
Changes the plain text inside an element. This replaces what was there. -
element.innerHTML = "<em>New</em> text"
Changes the HTML inside an element (use carefully). -
img.src = "image.png"andimg.alt = "A description"
Sets an attribute directly as a property. -
element.setAttribute("src", "cat.png")
Another way to change an attribute. -
element.value
Reads or sets the value of an input, textarea, or select.
3. Changing CSS with JavaScript
Every CSS property can be set through element.style. Property names with a hyphen become camelCase: background-color becomes backgroundColor. The value is always a string, units included.
document.body.style.backgroundColor = "lightblue"
// change the background color of the whole pagepanel3.style.width = "400px"
// set the width of an elementpanel1.style.transform = "translateX(0)"
// move an element (see section 8)document.querySelector("h1").style.color = "red"
// change the text color of the first <h1>box.style.border = "2px solid black"
// add a border around the elementdocument.querySelector(".demo").style.fontSize = "24px"
// change the font size of the first element with class="demo"
Building a value from a variable. Join strings and numbers with +, and don't forget the unit:
panel2.style.transform = `translateX(${distance}px)`;
// if distance is -300, this sets "translateX(-300px)"
Note: element.style only reads and writes inline styles (styles set by JavaScript or in a style="" attribute). It can't see what your stylesheet says. Styles set this way override the stylesheet.
4. Toggling Classes
Instead of setting many styles one by one in JavaScript, define a class in CSS and switch it on or off. JavaScript decides when a class goes on or off. CSS decides what the class looks like. This is how most professional interactive pages work.
Reading the chain: menu.classList.toggle("open")
menu: the element you selected.classList: that element's list of classes.toggle("open"): an action on that list, which flipsopenon or off
-
element.classList.add("active")
Adds a class. Does nothing if it's already there. -
element.classList.remove("active")
Removes a class. Does nothing if it isn't there. -
element.classList.toggle("active")
Adds the class if it's missing, removes it if it's there. Perfect for on/off buttons. -
element.classList.replace("small", "large")
Swaps one class for another.
No dot in JavaScript. In CSS you write .open. In classList you write just "open". (In querySelector you do use the dot, because it takes a CSS selector.)
No space in the CSS. #menu.open means one element with the id menu and the class open. With a space, #menu .open means an element with class open inside the menu.
5. Listening for Clicks
-
element.addEventListener("click", function () { ... })
Runs the function every time the element is clicked.
Any element can be clicked, not just buttons.
6. Show / Hide Elements
-
element.style.display = "none"// hide it
element.style.display = "block"// show it -
element.hidden = true// another way to hide
element.hidden = false// show -
element.classList.toggle("hidden")// with.hidden { display: none; }in your CSS
To make one button both show and hide, read the current state and do the opposite:
7. Creating & Removing Elements
Adding an element is always three steps: create it → fill it → put it on the page.
-
document.createElement("p")
Creates a new element (not on the page yet). -
parent.appendChild(element)
Adds the new element inside a parent, at the end. Each click adds another one below the last. -
parent.children.length
How many elements are inside the parent. Useful for numbering. -
element.remove()
Removes an element from the page. -
parent.lastElementChild
The last element inside the parent, ornullif it's empty.
8. Moving & Sliding Elements
The slide-out menu and the side panels use the same idea: start the element partly or fully out of view, then move it back with transform.
-
transform: translateX(100%)
Moves an element to the right by its own full width. Negative values move it left.translateX(0)puts it back where it normally sits. -
transition: transform 0.4s
Animates the change instead of jumping. Put it on the element's base rule so it works in both directions.transition: all 0.5sanimates every property that changes, such as width.
9. CSS Transform & Transition
Transform: move, resize, turn
transform changes how an element looks without changing the layout. Other elements don't move to make room.
-
translateX(100px)/translateY(20px)/translate(50px, 20px)
Moves the element. Negative values move left or up.%is a percentage of the element's own size. -
scale(1.5)
Resizes it.1is normal size,2is double,0.5is half. No unit. -
rotate(45deg)
Turns it.360degis a full turn. -
skewX(20deg)
Slants it. -
rotateY(180deg)
Flips it in 3D, like turning over a card.
Combine functions in one line, separated by spaces:
transform: translateX(100px) rotate(45deg) scale(1.2);
Watch out: setting transform replaces the whole value. If an element is rotated and you set transform: scale(2), the rotation is lost. Include every function you want to keep.
Transition: animate the change
Without a transition, a change happens instantly. With one, the browser animates from the old value to the new value.
-
transition: transform 0.4s;
Animates changes totransformover 0.4 seconds. -
transition: all 0.5s;
Animates every property that changes (color, width, transform...). -
transition: transform 0.4s ease-in-out 0.2s;
Full form: property, duration, easing (ease,linear,ease-in,ease-out,ease-in-out), and delay.
Put the transition on the base rule (not the class you add), so it animates in both directions: on and off.
Not everything animates. Colors, sizes, positions, opacity, and transform do. display does not: it jumps. To fade something out, animate opacity instead.
Together
/* CSS */
#box {
transition: transform 0.4s; /* on the base rule */
}
#box.active {
transform: rotate(45deg) scale(1.2);
}
// JS: switch the class...
box.classList.toggle("active");
// ...or set the transform directly
box.style.transform = "translateX(200px)";
Project Introduction: Clickable Page (5%) DUE: Week 6 — 9/30
Build a single web page that responds to user interaction. Clicking elements should trigger visible changes such as content updates, CSS transitions, color or style changes, animated movement, or the appearance and disappearance of elements.
You may start from the Clickable Page Template or build your own layout.
Plan the logic in plain English before writing code. Your grade will emphasize clear logic, working JavaScript, purposeful interaction, and a coherent visual design.
Minimum Requirements
- At least three clickable elements
- At least three visible changes produced with JavaScript
- DOM selection and manipulation
- At least one CSS transition or animated change
- Numbered logic steps in a comment before the script
- No AI-generated code
Logic Steps (required)
At the very top of your <script> tag, before any code, write your numbered logic steps as a commented list. Example:
/*
1. Select the button and the box.
2. When the button is clicked, run a function.
3. Inside the function, toggle the "active" class on the box.
4. The .active class in CSS changes color and size with a transition.
5. Also change the button's text to say "On" or "Off".
*/
This comment block is part of your grade. Without it, the project is considered incomplete.
Workshop (Next Monday)
Bring your idea and a first draft of your logic steps. We'll work them out together and start coding. During the workshop you may:
- Use Google and documentation (MDN, W3Schools) to look up specific syntax.
- Use AI to explain a specific step or concept — not to generate your project code.
- Use the Console constantly to check selections and debug.
Some starting ideas
- Mood switcher: buttons change the page's colors, fonts, and a headline.
- Reveal cards: click a card to flip it or reveal hidden text. I will demo how to flip cards next week.
- Toggle gallery: buttons show/hide groups of images.
- Slide-out menu: a button slides a nav panel in and out.
- Weird art toy: clicks move, grow, recolor, or multiply elements. The stranger the better.