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.