Exercises
Objectives
This chapter introduces no new concepts. It’s a chance to practice everything from this module: selecting, creating, modifying, and traversing elements, and reading form values.
All exercises use this starting HTML:
<div id="app">
<h1 id="heading">Store</h1>
<ul id="cart">
<li class="item">Apples - $3</li>
<li class="item">Bread - $2</li>
<li class="item">Milk - $4</li>
</ul>
<button id="checkout" class="btn">Checkout</button>
</div>
Exercises
-
Select
#headingand log its.textContent. Check: it logsStore. -
Change
#heading’s.textContentto"Welcome to the Store". Check: logging.textContentagain shows the new text. -
Select every element with class
itemusingquerySelectorAll()and log how many there are. Check:3. -
Loop over that same NodeList with
.forEach()and log each item’s.textContent. Check: three lines,Apples - $3,Bread - $2,Milk - $4. -
Create a new
<li>with classitemand text"Eggs - $5", and append it to#cart. Check:document.querySelectorAll(".item").lengthis now4. -
Select
#checkoutand use.parentElementto log its parent’sid. Check:app. -
Use
.closest("#app")starting from#checkoutand confirm it returns the same element asdocument.getElementById("app"), using===. Check:true. -
Add a class
disabledto#checkoutusing.classList.add(), then log.className. Check:btn disabled. -
Use
.classList.toggle("disabled")on#checkouttwice in a row, logging.classNameafter each call. Check: first log isbtn(removed since it was already there), second log isbtn disabled(added back). -
Select the first
.itemwithdocument.querySelector(".item"), then use.nextElementSiblingto log the second item’s.textContent. Check:Bread - $2. -
Set
#checkout’s.style.backgroundColorto"green". Check:document.querySelector("#checkout").getAttribute("style")includesbackground-color: green. -
Given a form
<form id="loginForm"><input type="text" name="email" value="test@example.com"><input type="checkbox" name="remember"></form>, select the email field throughform.elements["email"]and log its.value. Check:test@example.com. -
Using the same form, set the
remembercheckbox’s.checkedtotrue, then log.checked. Check:true. -
Create a
<div>, set its.innerHTMLto"<em>careful</em>", then log.textContent. Check:careful(the tag disappears from.textContent, since.textContentonly ever returns the text, never the markup). -
Create a
<div>containing the text"Visible"followed by a<span style="display: none">Hidden</span>. Log.textContent, then log.innerText. Check:.textContentincludes both"Visible"and"Hidden",.innerTextincludes only"Visible".
Recap
You can now select single or multiple elements, create and modify elements, move around the DOM tree, and read values out of a form. That’s the full toolkit for reading and changing a page. Handling what a user actually does with it is next.
Next module: Events, responding to clicks, key presses, and form submissions.