In-Depth Guide to DOM Manipulation

Once you have selected an element and stored it in a variable, you have a powerful object that gives you full control over that part of your webpage. Let's cover the three main categories of manipulation:

  1. Editing What's Inside (Content & HTML)
  2. Editing the Tag Itself (Attributes, Classes, and Styles)
  3. Editing the Page Structure (Creating, Adding, and Removing Elements)

Part 1: Editing the Content Inside an Element

This is about what the user sees inside an element's opening and closing tags.

HTML Snippet for this section:

<div id="welcome-box">
  Please log in to see your messages.
</div>

// We've selected our target element
const welcomeBox = document.getElementById('welcome-box');

A. .textContent (For Plain Text - The Safe Default)

// Reading the text content
console.log(welcomeBox.textContent); // "Please log in to see your messages."

// Writing new text content
welcomeBox.textContent = "Welcome back, Alice!";

The Security Benefit: When you set .textContent, the browser treats your string as plain text. This is safe because it prevents malicious code from being executed.

// Even if this string came from a hacker...
const maliciousInput = "<script>alert('hacked!');</script>";

welcomeBox.textContent = maliciousInput;
// The browser will LITERALLY display the text: "<script>alert('hacked!');</script>"
// It will NOT run the script.

B. .innerHTML (For HTML - Powerful but Dangerous)