JavaScript Lesson 7: The DOM — Changing a Web Page

📎 This article includes 1 downloadable practice file ↓

⏱ 1 min read

📘 JavaScript Beginner Course · Lesson 7 of 8

In the browser, JavaScript can read and change the page through the DOM (Document Object Model), the tree of elements the browser builds from HTML.

“`javascript
const $ = id => document.getElementById(id);
$(“calc”).addEventListener(“click”, () => {
const amount = Number($(“qty”).value) * Number($(“rate”).value);
$(“out”).textContent = `Amount Rs ${amount.toLocaleString(“en-IN”)}`;
const li = document.createElement(“li”);
li.textContent = amount;
$(“list”).prepend(li);
});
“`

  • document.getElementById / querySelector(".class") find elements.
  • .value reads inputs (always text: convert with Number()).
  • addEventListener("click", fn) runs code on events.
  • textContent changes text safely; avoid innerHTML with user input.
⚠️ Setting innerHTML with text typed by users can run injected code (XSS). Use textContent for plain text.

Practice

Download the HTML file, open it in your browser and press Calculate. Then add a discount field.

📎 Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong