7 min read
intermediate

JavaScript DOM — Controlling the Page

Learn how to use JavaScript to change HTML elements, respond to clicks, and build interactive web pages.

What is the DOM?

The DOM (Document Object Model) is how JavaScript sees your HTML page. It turns your HTML into a tree of objects that JavaScript can read and change. When you click a button and something changes on the page — that's JavaScript manipulating the DOM.

Finding Elements

javascript
// By ID (returns one element)
const title = document.getElementById("title");

// By class (returns a list)
const cards = document.querySelectorAll(".card");

// By CSS selector (returns first match)
const btn = document.querySelector("button.primary");

// Changing content
title.innerText = "New Title!";
title.innerHTML = "<em>Italic Title</em>";

// Changing styles
title.style.color = "purple";
title.style.fontSize = "32px";

// Adding/removing CSS classes
title.classList.add("active");
title.classList.remove("hidden");
title.classList.toggle("dark-mode");

Handling Events (Clicks, Typing, etc.)

javascript
const button = document.getElementById("myBtn");

// Click event
button.addEventListener("click", () => {
  alert("You clicked!");
});

// Input event (typing)
const input = document.getElementById("search");
input.addEventListener("input", (e) => {
  console.log("You typed:", e.target.value);
});

// Keyboard event
document.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
    console.log("Enter pressed!");
  }
});

Creating Elements Dynamically

javascript
// Create a new element
const card = document.createElement("div");
card.className = "card";
card.innerHTML = `
  <h3>New Card</h3>
  <p>This was created with JavaScript!</p>
`;

// Add it to the page
document.getElementById("container").appendChild(card);

// Remove an element
card.remove();
Pro Tip

Use addEventListener() instead of onclick attributes in your HTML. It's cleaner, lets you add multiple handlers, and separates your JavaScript from your HTML.

Try It Yourself

Build a simple to-do list: an input field, an "Add" button, and a list. When the button is clicked, create a new <li> element with the input text, add it to the list, and clear the input. Bonus: add a delete button on each item.

Ready to build?

Put what you learned into practice — pick a project and start coding.

Start Building Free