JavaScript Lesson 7: The DOM β€” Changing a Web Page

JavaScript Lesson 7: The DOM β€” Changing a Web Page featured illustration

πŸ“Ž This article includes 1 downloadable practice file ↓

⏱ 1 min read

πŸ“˜ JavaScript Beginner Course Β· Lesson 7 of 8

Advertisement

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.

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.

Advertisement

πŸ“Ž 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