DOM Manipulation - Changing Your Web Pages Dynamically

Master DOM manipulation to change content, styles, classes, and structure of your web pages with JavaScript

Now let's learn how to change your web pages after they've loaded!


7. DOM Manipulation

What is DOM Manipulation?

DOM manipulation means using JavaScript to change the content, structure, or style of your HTML page after it has loaded.


7.1 Changing Text Content

Using textContent

<h1 id="title">Original Title</h1>
<p id="description">Original description</p>
const title = document.querySelector("#title");
const description = document.querySelector("#description");

// Change text
title.textContent = "New Title";
description.textContent = "This is the new description.";

Using innerText (similar to textContent)

const heading = document.querySelector("h1");
heading.innerText = "Updated Heading";

Note: textContent vs innerText:

  • textContent: Shows all text, including hidden elements
  • innerText: Shows only visible text
  • Both work for basic text changes

7.2 Changing HTML Content

Using innerHTML

<div id="container">
  <p>Old content</p>
</div>
const container = document.querySelector("#container");

// Replace entire HTML content
container.innerHTML = "<h2>New Heading</h2><p>New paragraph</p>";

// Add to existing content
container.innerHTML += "<p>Additional paragraph</p>";

⚠️ Warning: Be careful with innerHTML when using user input - it can create security risks!


7.3 Changing CSS Styles

Using the style property

<div id="box">This is a box</div>
const box = document.querySelector("#box");

// Change individual styles
box.style.backgroundColor = "lightblue";
box.style.color = "white";
box.style.padding = "20px";
box.style.fontSize = "18px";
box.style.border = "2px solid navy";

// Note: CSS properties with hyphens become camelCase
// CSS: background-color → JavaScript: backgroundColor
// CSS: font-size → JavaScript: fontSize

Practical example:

const button = document.querySelector("#myButton");

button.addEventListener("click", () => {
  button.style.backgroundColor = "green";
  button.style.color = "white";
  button.style.fontSize = "20px";
});

7.4 Working with CSS Classes

Using classList

This is the better way to change styles (instead of style property).

<div id="box" class="container">Content</div>
/* In your CSS file */
.highlight {
  background-color: yellow;
  font-weight: bold;
}

.large {
  font-size: 24px;
}
const box = document.querySelector("#box");

// Add a class
box.classList.add("highlight");

// Remove a class
box.classList.remove("container");

// Toggle a class (add if not present, remove if present)
box.classList.toggle("large");

// Check if class exists
if (box.classList.contains("highlight")) {
  console.log("Box is highlighted!");
}

// Add multiple classes at once
box.classList.add("highlight", "large");

Why use classList instead of style?

  • Keeps styles in CSS where they belong
  • Easier to manage and reuse
  • Better performance
  • Cleaner code

7.5 Showing and Hiding Elements

Method 1: Using style.display

<div id="content">
  <p>This content can be hidden.</p>
</div>
<button id="toggleBtn">Toggle Content</button>
const content = document.querySelector("#content");
const toggleBtn = document.querySelector("#toggleBtn");

toggleBtn.addEventListener("click", () => {
  if (content.style.display === "none") {
    content.style.display = "block"; // Show
  } else {
    content.style.display = "none";  // Hide
  }
});

Method 2: Using a CSS class (better)

.hidden {
  display: none;
}
const content = document.querySelector("#content");
const toggleBtn = document.querySelector("#toggleBtn");

toggleBtn.addEventListener("click", () => {
  content.classList.toggle("hidden");
});

7.6 Getting and Setting Attributes

<img id="myImage" src="old.jpg" alt="Old Image">
<input id="email" type="text" placeholder="Enter email">
const image = document.querySelector("#myImage");
const input = document.querySelector("#email");

// Get attribute value
console.log(image.src);           // "old.jpg"
console.log(input.placeholder);   // "Enter email"

// Set attribute value
image.src = "new.jpg";
image.alt = "New Image";
input.placeholder = "Your email here";

// Using getAttribute and setAttribute (alternative)
const oldSrc = image.getAttribute("src");
image.setAttribute("src", "another.jpg");

7.7 Creating and Adding Elements

Creating new elements

// Create a new element
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
newParagraph.classList.add("info");

// Add it to the page
document.body.appendChild(newParagraph);

More complex example:

// Create a new div with content
const newDiv = document.createElement("div");
newDiv.classList.add("card");

const heading = document.createElement("h3");
heading.textContent = "Card Title";

const text = document.createElement("p");
text.textContent = "This is card content.";

// Build the structure
newDiv.appendChild(heading);
newDiv.appendChild(text);

// Add to page
const container = document.querySelector("#container");
container.appendChild(newDiv);

7.8 Removing Elements

<div id="message">This message will disappear.</div>
<button id="removeBtn">Remove Message</button>
const message = document.querySelector("#message");
const removeBtn = document.querySelector("#removeBtn");

removeBtn.addEventListener("click", () => {
  message.remove(); // Remove the element
});

🎯 Key Takeaways

Variables store data (let for changing values, const for constants)

Functions organize reusable code

Arrays store ordered lists of values (starting at index 0)

DOM is the tree structure representing your HTML

querySelector finds HTML elements using CSS selectors

Events let you respond to user actions (clicks, typing, etc.)

DOM Manipulation changes content, styles, and structure dynamically


Final Tips

🔹 Link your JavaScript file properly and always test your code in the browser!

🔹 Use console.log() to debug and see what's happening

🔹 Practice by building small interactive projects

🔹 Keep your code organized with functions

🔹 Use meaningful variable and function names


Congratulations! 🎉

You've completed Session 3 - JavaScript Basics!

You now know how to:

  • Connect JavaScript to HTML
  • Use variables, functions, and arrays
  • Select and manipulate DOM elements
  • Handle user events
  • Change styles and content dynamically

Keep practicing and building! The more you code, the better you'll get. 🚀