Manipulating Styles & Content

Manipulating Styles & Content in JavaScript: Once you've found an element, you can change what's inside it or how it looks. innerHTML: Changes the HTML inside.

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

  1. XSS Attacks: Using innerHTML with user-provided text. A hacker could inject a <script> tag and steal passwords! Use textContent for user data.
  2. Hyphens in JS: In CSS you write background-color. In JavaScript you MUST use camelCase: backgroundColor.
  3. Overwriting classList: Using className = "new-class" deletes all existing classes! Always use classList.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 .error class in CSS and do classList.add("error") in JS.
  • Batch Layout Changes: If you are changing 5 styles, apply them all at once to avoid "Jank" (flickering).

Practice Exercises

  1. The Text Toggler: Create a button that changes its text between "Play" and "Pause" every time it's clicked.
  2. The Style Transformer: Create a box that changes its background color to a random color every time the mouse moves inside it.
  3. The Safe Input: Create an input field and a div. Make the div show exactly what is typed in the input, but use textContent to ensure it's safe.