Codetainer LogoCodetainer Acad

Lessons

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 text
  • element.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 only
  • innerHTML = can inject HTML (use carefully)
  • setAttribute() = change/add any attribute
  • element.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!

CodetainerAcad