Web Fundamentals: JavaScript and the DOM

Site Admin · 11 Sep 2026 · 5 views

JavaScript Runs in the Browser

JavaScript is the language of interactivity on the web. It can fetch data, validate forms, animate the page, and react to clicks. Browsers expose a living tree of the page called the Document Object Model, or DOM. Every element on the page is a node in that tree, and JavaScript can read, create, and remove nodes.

Variables and Functions

let counter = 0;
const title = "GroovyGrails";

function greet(name) {
    return "Hello " + name;
}

alert(greet("Reader"));

let declares a variable that can change, while const declares one that cannot be reassigned. Functions are declared with the function keyword and can be passed around like any other value.

Finding and Changing Elements

To change the page, first find the element you want. The most common helpers are getElementById, querySelector, and querySelectorAll.

const heading = document.getElementById("greeting");
heading.textContent = "Updated by JavaScript";
heading.style.color = "green";

document represents the whole page. getElementById returns the element with that id, and textContent swaps out its text. The style property gives access to the element inline styles, with css property names written in camel case.

Responding to Events

Interactivity is driven by events. addEventListener registers a function that runs when the event happens.

const button = document.getElementById("submit");
button.addEventListener("click", () => {
    alert("Button clicked");
});

The arrow function is the modern way to write a callback. Events such as click, input, and submit fire constantly, and your listener is the code that reacts.

Creating Elements

const item = document.createElement("li");
item.textContent = "A new item";
document.getElementById("list").appendChild(item);

createElement builds a node in memory, textContent fills it, and appendChild attaches it to the list. That sequence of create, configure, attach is the pattern behind most dynamic lists and live updates.

Key Points

  • JavaScript manipulates a live DOM tree representing the page.
  • let and const declare variables; functions bundle reusable logic.
  • Select elements with getElementById or querySelector.
  • addEventListener binds callbacks to events like click.
Share this post:

Comments (0)

Please login or register to comment.