Lesson 22: Modifying Content and Attributes
π οΈ Lesson 22: Modifying Content and Attributes
Once you've selected elements from the DOM, it's time to modify their content and attributes. This is how we make our pages dynamic and responsive.
π Changing Text Content
You can update the text inside an element using:
element.textContentβ sets or gets the plain textelement.innerHTMLβ allows you to add HTML tags inside
// Assume we selected this: <p id="intro">Hello</p>
const intro = document.getElementById("intro");
intro.textContent = "Welcome to our site!"; // Just plain text
intro.innerHTML = "<strong>Bold greeting!</strong>"; // With HTML
β οΈ Warning: Be careful using innerHTML with user-generated content β it can expose your site to XSS (Cross-Site Scripting) attacks!
π Changing Attributes
There are two main ways to change attributes like src, href, or alt:
1. setAttribute()
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
link.setAttribute("target", "_blank");
2. Directly via properties
const image = document.querySelector("img");
image.src = "logo.png";
image.alt = "Our company logo";
Both methods work, but using setAttribute is often clearer when you want to set multiple or dynamic attributes at once.
π― Use Case Example
Suppose you want to update a CTA (Call-to-Action) button when a user logs in:
const cta = document.getElementById("cta-button");
cta.textContent = "Go to Dashboard";
cta.setAttribute("href", "/dashboard");
cta.classList.add("bg-green-500");
π§ Summary
textContent= plain text onlyinnerHTML= can inject HTML (use carefully)setAttribute()= change/add any attributeelement.property= direct access (e.g.element.src)
Next, weβll bring the page to life with event listeners. Time to make your site respond to clicks, scrolls, and keypresses!