Concept Explanation
Once you've found an element, you can change what's inside it or how it looks.
- innerHTML: Changes the HTML inside. (Powerful but potentially dangerous!)
- textContent: Changes just the text. (Slower but much safer).
- classList: The best way to change styles by adding/removing CSS classes.
Syntax or Core Structure
Modifying Content
const p = document.querySelector("p");
p.textContent = "New text!"; // Safe
p.innerHTML = "<strong>New bold text!</strong>"; // Renders HTML
Modifying Style (The Right Way)
const card = document.querySelector(".card");
// Good: Uses CSS classes
card.classList.add("highlight");
card.classList.toggle("active");
// Okay (but messy): Inline styles
card.style.backgroundColor = "gold";
Common Mistakes
- XSS Attacks: Using
innerHTMLwith user-provided text. A hacker could inject a<script>tag and steal passwords! UsetextContentfor user data. - Hyphens in JS: In CSS you write
background-color. In JavaScript you MUST use camelCase:backgroundColor. - Overwriting classList: Using
className = "new-class"deletes all existing classes! Always useclassList.add()to keep what's already there.
Best Practices
- Prefer textContent: It's faster and protects you from security risks.
- CSS for Styling: Don't use
.style.color = "red"in JS. Instead, create a.errorclass in CSS and doclassList.add("error")in JS. - Batch Layout Changes: If you are changing 5 styles, apply them all at once to avoid "Jank" (flickering).
Practice Exercises
- The Text Toggler: Create a button that changes its text between "Play" and "Pause" every time it's clicked.
- The Style Transformer: Create a box that changes its background color to a random color every time the mouse moves inside it.
- The Safe Input: Create an input field and a div. Make the div show exactly what is typed in the input, but use
textContentto ensure it's safe.