SmartCodingTips

Changing Content with JavaScript

JavaScript can dynamically change the content of HTML elements using the DOM. This is useful for interactive web apps, user feedback, and live updates.

πŸ“ textContent

Safely sets or gets the text content of an element. It does not render HTML.

document.querySelector("p").textContent = "New text goes here.";

🌐 innerHTML

Sets or gets HTML inside an element. Use with caution as it can be a security risk (XSS).

document.getElementById("output").innerHTML = "<strong>Bold Text</strong>";

βœ… innerText (Less Common)

Similar to textContent but affected by CSS (like display:none).

const title = document.querySelector("h1");
title.innerText = "Updated Title";

πŸ“¦ Updating Inputs and Forms

document.querySelector("input").value = "New input value";

🧠 When to Use Each

  • textContent – Best for plain text.
  • innerHTML – Needed when inserting HTML elements.
  • innerText – Reflects what’s visible to users.
πŸ’‘ Tip: Use textContent for security and performance. Avoid innerHTML unless HTML rendering is required.