⚡0 XP🔥0

The DOM and Events

Lesson 6 of 7 ⏱ 4 min read ✎ 1 exercises ❓ 5-question quiz ▶ Runs HTML

Make pages interactive - select elements with querySelector, change text, styles and classes, create elements, handle clicks, typing and form submit events, and save data with localStorage.

What is the DOM?#

When the browser loads HTML, it builds a tree of objects called the DOM (Document Object Model). JavaScript can read and change this tree - and the page updates instantly.

document
 └── html
      ├── head ── title
      └── body
           ├── h1
           └── button
हिंदी में समझें

DOM browser के अंदर बना HTML page का पेड़ (tree) है। हर tag एक object बन जाता है। JavaScript इस पेड़ की किसी भी डाली (element) को ढूंढ सकती है, उसका text या रंग बदल सकती है, नई डाली जोड़ सकती है - और page तुरंत बदल जाता है।

Selecting and changing elements#

▶ Try it YourselfHTML
Ctrl + Enter to run
Task Code
select one / all document.querySelector("css"), document.querySelectorAll("css")
text el.textContent = "Hi"
HTML (trusted content only) el.innerHTML = "<b>Hi</b>"
attribute img.src = "a.png", el.setAttribute("aria-label", "Close")
input value input.value
style el.style.display = "none"
classes el.classList.add("on"), .remove("on"), .toggle("on")
Tip

Put your <script> at the end of <body> (or use <script defer src="app.js"> in the head) so the elements already exist when the code runs.

Events#

An event is something that happens - a click, a key press, a form submit, the page finishing loading. addEventListener runs your function when it happens.

▶ Try it YourselfHTML
Ctrl + Enter to run

Common events: click, input (every keystroke), change, submit, keydown, mouseover, scroll, DOMContentLoaded.

The callback receives an event object (e): e.target is the element, e.key is the key pressed, e.preventDefault() cancels the browser's default action.

Creating elements - a to-do list#

▶ Try it YourselfHTML
Ctrl + Enter to run
Common Mistake

Never put text typed by a user into innerHTML. Someone could type <img src=x onerror="stealCookies()">. Use textContent or createElement.

Event delegation#

Instead of one listener per button, put one listener on the parent and check e.target:

list.addEventListener("click", (e) => {
  if (e.target.matches("button.delete")) e.target.closest("li").remove();
});

This also works for items added later.

Saving data with localStorage#

localStorage keeps small data in the browser even after closing the tab - Vindhyaedu saves your XP and progress this way.

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");      // "dark" (always a string)
localStorage.setItem("tasks", JSON.stringify(["Study", "Practice"]));
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
localStorage.removeItem("theme");

Summary#

  • The DOM is the page as objects; select with querySelector / querySelectorAll.
  • Change textContent, value, style and classList; create with createElement + append.
  • addEventListener("click" | "input" | "submit", fn); use e.preventDefault() for forms.
  • Use textContent for user input; save small data with localStorage + JSON.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Mobile number checker

Before a form is sent, JavaScript usually checks the inputs. Write isValidMobile(s) that returns true when s is a 10-digit Indian mobile number starting with 6, 7, 8 or 9 (spaces at the ends should be ignored). The given loop must print:

9876543210 -> true
5876543210 -> false
98765 -> false
 9123456789  -> true
98765abcde -> false
Expected output:
9876543210 -> true
5876543210 -> false
98765 -> false
 9123456789  -> true
98765abcde -> false

Quick Quiz

Q1.

What is the DOM?

Q2.

Which line selects the first element with class card?

Q3.

Why is textContent safer than innerHTML for user input?

Q4.

In a form submit handler, what does event.preventDefault() do?

Q5.

What does element.classList.toggle("dark") do?