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:
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');
.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.
.innerHTML (For HTML - Powerful but Dangerous)