Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What Is the DOM?
  • - Selecting Elements
  • - Changing Content and Style
  • - Handling Events
  • - Creating and Appending Elements
  • - Removing Elements
  • - Mini Challenge
  • - Key Takeaway

10. DOM Manipulation Basics

Level: BeginnerDuration: 25m

What Is the DOM?

The Document Object Model (DOM) is a structured representation of your web page. JavaScript can use it to read and modify HTML elements dynamically — meaning your site can respond to user actions in real time.

html
<h1 id="title">Hello World</h1>
<button id="btn">Click Me</button>

The DOM treats every element like a JavaScript object you can access and manipulate.

Selecting Elements

To change an element, you first need to select it. The most common methods are `getElementById`, `querySelector`, and `querySelectorAll`.

javascript
const title = document.getElementById("title");
const button = document.querySelector("#btn");

Changing Content and Style

You can easily change an element’s text, HTML, or style properties.

javascript
title.textContent = "Welcome to JavaScript!";
title.style.color = "lime";
title.style.fontSize = "2rem";

Handling Events

Events let your page respond to user actions like clicks, hovers, and keypresses.

javascript
button.addEventListener("click", () => {
  title.textContent = "You clicked the button!";
  title.style.color = "pink";
});

Creating and Appending Elements

You can create new elements and insert them into the DOM using `createElement()` and `appendChild()`.

javascript
const newPara = document.createElement("p");
newPara.textContent = "This paragraph was added with JavaScript!";
document.body.appendChild(newPara);

Removing Elements

You can remove existing elements with `.remove()`.

javascript
title.remove(); // Removes the <h1> element

Mini Challenge

Create a button that, when clicked, adds a new `<li>` item to a `<ul>` list. Bonus: make each new item have a random background color!

html
<ul id="list"></ul>
<button id="add">Add Item</button>
javascript
const list = document.getElementById("list");
const button = document.getElementById("add");

button.addEventListener("click", () => {
  const newItem = document.createElement("li");
  newItem.textContent = `Item ${list.children.length + 1}`;
  newItem.style.background = `hsl(${Math.random() * 360}, 70%, 60%)`;
  list.appendChild(newItem);
});

Key Takeaway

DOM manipulation is what makes web pages dynamic and interactive. By selecting elements, listening for events, and updating the DOM, you bring your pages to life.

MDN Docs: DOM Manipulation Guide