Web Development courseLesson 7 of 20 · tap to see all lessons
Web Development · Beginner
The DOM and Interactive Web Pages: Selecting Elements, Events, and Form Validation in JavaScript
Use JavaScript to find and change elements on a page, create new ones, respond to clicks and typing with event listeners, and validate forms before they're sent.
- Qyubie Learn Editorial Team
- Published
- 14 min read
Includes 2 exercises and 1 quick check you can do right here.
In the last lesson, JavaScript only printed to the console. Now it gets its hands on the page. When the browser loads HTML, it builds a tree of objects called the DOM (Document Object Model), and JavaScript can read and change that tree: update text, show and hide sections, add list items, and check a form before it's sent. This is what makes a page feel interactive, and it's what React automates in lessons 12–13.
By the end of this lesson you will be able to:
- explain what the DOM is,
- select elements and change their text, attributes, classes, and styles,
- create and remove elements,
- respond to events such as clicks, typing, and form submission, and
- validate a form in the browser and show helpful messages.
Each example below runs live in a preview. Click the buttons and type in the inputs.
What the DOM is
The browser turns this HTML:
<body>
<h1>Tasks</h1>
<ul>
<li>Read lesson 7</li>
</ul>
</body>into a tree of nodes:
document
└── html
└── body
├── h1 ── "Tasks"
└── ul
└── li ── "Read lesson 7"Each element is an object with properties (textContent, className, value) and methods (addEventListener, remove). Change the object and the browser updates the screen at once. The global document object is the entry point to the whole tree.
Selecting elements
Try it · HTML & CSS
document.querySelector(selector)returns the first element matching a CSS selector, ornullif none does.document.querySelectorAll(selector)returns all matches; loop through them withforEach.- The selectors are the same as in CSS (lesson 3):
#id,.class,nav a, and so on. (Older code also usesgetElementById("title").)
If querySelector finds nothing, it returns null, and the next line fails with Cannot set properties of null. The usual causes are a typo in the selector, or a script that runs before the element exists. That's why scripts go at the end of the <body>, or use defer.
Changing content, attributes, classes, and styles
Try it · HTML & CSS
| To change | Use |
|---|---|
| text | el.textContent = "..." |
| HTML inside | el.innerHTML = "<b>...</b>" (only with HTML you trust) |
| an attribute | el.setAttribute("href", "..."), or the property: el.href = "..." |
| CSS classes | el.classList.add("x"), .remove("x"), .toggle("x"), .contains("x") |
| one style | el.style.backgroundColor = "red" (CSS names in camelCase) |
| a form field's value | input.value |
Prefer classList over style. Keep the look in CSS, and let JavaScript only switch classes on and off.
Prefer textContent over innerHTML for anything a user typed. innerHTML treats the text as HTML, so <script> or <img onerror=...> in user input would run: the same XSS problem you prevented with htmlspecialchars in PHP.
Creating and removing elements
Try it · HTML & CSS
The pattern is: create with document.createElement, fill it (text, classes, attributes), then insert it with append (at the end), prepend (at the start), or before/after. el.remove() takes an element off the page.
Events and event listeners
An event is something that happens: a click, a key press, a form submission, the page finishing loading. You react to one with addEventListener(type, function):
Try it · HTML & CSS
The function is a callback: you give it to the browser, and the browser calls it each time the event happens. Notice the pattern every interactive page follows: keep the data in a variable (count), change the data when an event happens, then update the page to match. React is built around exactly this idea, which it calls state.
Common events:
| Event | Fires when |
|---|---|
click | an element is clicked (or tapped) |
input | the value of an input changes, on every keystroke |
change | a select, checkbox, or input is changed and left |
submit | a form is submitted |
keydown | a key is pressed |
mouseover / mouseout | the pointer enters / leaves an element |
DOMContentLoaded | the HTML has been fully read (on document) |
The callback receives an event object with details about what happened:
Try it · HTML & CSS
event.target is the element the event happened on. Other useful parts are event.key (for keyboard events) and event.preventDefault(), which cancels what the browser would normally do, such as submitting a form.
Quick check
A small app: a to-do list
Selecting, creating, and events together make a complete little app:
Try it · HTML & CSS
Add a few tasks, click one to mark it done, and double-click to delete it. Listening for the form's submit (instead of the button's click) means pressing Enter works too, and event.preventDefault() stops the browser from sending the form to a server.
Form validation and interactive behavior
In lesson 5, PHP validated forms on the server, and that check must always stay. Validating in the browser as well gives instant feedback, before a round trip to the server.
Built-in validation comes free with HTML attributes: required, type="email", minlength, min/max, and pattern. The browser checks them on submit and shows its own message.
JavaScript validation lets you write your own rules and messages, and show them where you want:
Try it · HTML & CSS
Things to notice:
novalidateon the form turns off the browser's built-in messages, so only yours appear.form.emailreaches the input whosenameisemail./^[^\s@]+@[^\s@]+\.[^\s@]+$/is a regular expression, a pattern for text..test(text)returns true if the text matches. This one only checks the general shape of an email; the server should check it properly.- Each error appears next to its field, and the field turns red. Errors disappear as the user fixes them.
- Validation here is only for convenience. Anyone can turn off JavaScript or send a request directly, so the server still validates everything (lesson 5).
Small touches like these make a form much nicer to use:
- show a password's strength as the user types (
inputevent), - disable the submit button while a request is being sent, so it can't be sent twice,
- show and hide extra fields depending on a choice (
changeevent on a select).
Try it
Exercise · HTML & CSS
Like button
Make the button count likes: each click adds 1 to the number in the #likes span, using addEventListener("click", ...) and textContent.
Hint
let likes = 0; const span = document.querySelector("#likes"); document.querySelector("#like").addEventListener("click", () => { likes++; span.textContent = likes; });
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
<button id="like">👍 Like</button>
<span id="likes">0</span> likes
<script>
let likes = 0;
const span = document.querySelector("#likes");
document.querySelector("#like").addEventListener("click", () => {
likes++;
span.textContent = likes;
});
</script>
Exercise · HTML & CSS
Character counter
Show how many characters are left (out of 100) as the user types in the textarea. Listen for the input event, and set the text of #left to 100 - length. Add the class warn when fewer than 10 are left.
Hint
In the listener: const left = 100 - bio.value.length; leftSpan.textContent = left; leftSpan.classList.toggle("warn", left < 10);
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
<style>.warn { color: #b42318; font-weight: bold; }</style>
<textarea id="bio" maxlength="100" rows="3" cols="40"></textarea>
<p><span id="left">100</span> characters left</p>
<script>
const bio = document.querySelector("#bio");
const leftSpan = document.querySelector("#left");
bio.addEventListener("input", () => {
const left = 100 - bio.value.length;
leftSpan.textContent = left;
leftSpan.classList.toggle("warn", left < 10);
});
</script>
Common mistakes
- Running a script before the HTML exists, so
querySelectorreturnsnull. Put the script at the end of the body, or usedefer. querySelector("title")when you meant"#title". Without#or., it looks for a<title>tag.- Calling the function instead of passing it:
addEventListener("click", update())runsupdateonce, immediately. WriteaddEventListener("click", update). - Forgetting
event.preventDefault()on a form handled with JavaScript, so the page reloads. - Putting user input into
innerHTML. UsetextContent. - Validating only in the browser.
Summary
- The DOM is the browser's tree of objects for the page;
documentis its root. querySelectorandquerySelectorAllfind elements with CSS selectors.- Change pages with
textContent, attributes,classList, andstyle; build them withcreateElement,append, andremove. addEventListener(type, callback)reacts toclick,input,submit, and more. The event object givestarget,key, andpreventDefault().- Validate forms in the browser for fast feedback, with messages next to each field, and always validate again on the server.
Next lesson: PHP and database integration: saving form data in a database, safely.