HTML•DOM Selection
DOM Manipulation: querySelector, textContent, and innerHTML
Learn how JavaScript interacts with the Document Object Model (DOM) to update page content dynamically.
Syntax
const el = document.querySelector("#myId");
el.textContent = "New text";
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| document.querySelector() | Method | Returns the first Element matching the CSS selector. |
| textContent | Property | Safely sets or reads text without XSS vulnerabilities. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing HTML locally:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; padding: 20px; text-align: center; }
#status-display { font-size: 20px; font-weight: bold; color: #0284c7; margin: 15px 0; }
button { padding: 10px 18px; border-radius: 6px; background: #0f172a; color: white; border: none; cursor: pointer; }
</style>
</head>
<body>
<h2>DOM Text Manipulation</h2>
<div id="status-display">Status: OFFLINE</div>
<button id="toggle-btn">Connect Server</button>
<script>
const statusDiv = document.querySelector("#status-display");
const toggleBtn = document.querySelector("#toggle-btn");
toggleBtn.addEventListener("click", () => {
statusDiv.textContent = "Status: ONLINE (Port 8080 Active)";
statusDiv.style.color = "#16a34a"; // Green
});
</script>
</body>
</html>Expected Output:
[Interactive UI: Clicking "Connect Server" Dynamically Updates Status to Green "ONLINE"]
How It Works: Step-by-Step
- Lines 16-17: document.querySelector selects DOM elements by CSS IDs.
- Lines 19-22: Click event listener mutates textContent and inline style.color.
Key Concepts
- Prefer textContent over innerHTML to prevent Cross-Site Scripting (XSS) vulnerabilities.
- querySelector accepts any standard CSS selector (.class, #id, div > p).
Common Mistake: Using innerHTML with untrusted user input
Injecting unescaped user input via innerHTML allows malicious script injection (XSS). Use textContent.
❌ Incorrect
el.innerHTML = userInput; // High severity XSS vulnerability!
✅ Correct
el.textContent = userInput; // Safe
Related HTML Tutorials & Compiler
DOM Event Listeners: addEventListener, Click, and Input Events
Respond to user actions using addEventListener for click, input, and keyup events.
DOM classList API: add, remove, and toggle CSS Classes
Mutate styles dynamically by toggling CSS classes with element.classList.
Dynamic DOM: document.createElement and appendChild
Generate dynamic HTML elements on the fly with document.createElement and append.
HTML Online Compiler
Open in Compilra IDE
Run and test HTML on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.