JS JavaScript

JavaScript: DOM Manipulation

What you will learn

How JavaScript in the browser can select, modify, create, and respond to HTML elements.

The Document Object Model (DOM) is the browser's tree representation of your HTML. JavaScript can walk this tree and change it.

Selecting elements

// By ID — fastest method for unique elements
const title = document.getElementById("main-heading");

// By CSS selector — very flexible
const button = document.querySelector(".submit-btn");  // first match
const allButtons = document.querySelectorAll("button"); // NodeList

// Old way (still common)
const paragraphs = document.getElementsByTagName("p");

Modifying content and style

title.textContent = "New Title";          // plain text
title.innerHTML = "<em>New</em> Title";    // HTML string
title.style.color = "blue";
title.classList.add("highlight");

Creating and adding elements

const div = document.createElement("div");
div.textContent = "Hello from JS";
div.className = "alert";
document.body.appendChild(div);

Events

button.addEventListener("click", (e) => {
    console.log("Button clicked!", e.target);
});

Quick check below!