Lesson 57 +15 XP

Changing HTML and CSS

Changing HTML and CSS

Once you have an element, you can change its content and styling.

Change text with innerHTML

document.getElementById("demo").innerHTML = "New text";

Change text only

textContent changes text without parsing HTML:

el.textContent = "Plain text";

Change an attribute

let img = document.querySelector("img");
img.src = "new-image.png";
img.alt = "A new image";

Change styles

let el = document.getElementById("demo");
el.style.color = "red";
el.style.fontSize = "20px";

CSS property names become camelCase: font-size becomes fontSize.

Change classes

el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");

TL;DR

  • innerHTML changes content.
  • Attributes are set by assignment: el.src = "...".
  • style properties use camelCase.
  • classList adds, removes, and toggles classes.