Once you have an element, you can change what it shows.
textContent
Sets or reads the plain text inside an element.
<p id="message">Waiting...</p>
<button id="go">Update</button>
<script>
const message = document.querySelector("#message");
document.querySelector("#go").addEventListener("click", () => {
message.textContent = "Done!";
});
console.log(message.textContent); // → Waiting...
</script>
textContent treats everything as text. If you set it to "<b>hi</b>", the user sees those angle brackets literally. That makes it safe for text that comes from users.
innerHTML
Sets or reads the HTML inside an element, and the browser parses it.
<div id="box"></div>
<script>
const box = document.querySelector("#box");
box.innerHTML = "<strong>Bold</strong> and <em>italic</em>";
console.log(box.children.length); // → 2
</script>
Handy for rendering your own templates, but dangerous with user data, because any HTML in it (including scripts in event attributes) will run. See textContent vs innerHTML: Safe Output.
innerText
Similar to textContent, but it respects CSS: hidden elements are skipped, and it reflects line breaks as displayed. It is slower because it needs layout. Prefer textContent unless you need that behaviour.
Comparing
| Property | Reads | Writes | Safe for user text |
|---|---|---|---|
textContent | all text, including hidden | text | Yes |
innerText | visible text only | text | Yes |
innerHTML | the HTML source | HTML (parsed) | No |
Building a list
<ul id="list"></ul>
<script>
const fruits = ["apple", "banana", "cherry"];
const list = document.querySelector("#list");
// Safe: build elements and use textContent
for (const fruit of fruits) {
const li = document.createElement("li");
li.textContent = fruit;
list.append(li);
}
</script>
You will meet createElement in Creating Elements.
Clearing an element
list.textContent = ""; // removes all children quickly
list.replaceChildren(); // modern, explicit way to do the same
Form fields use value
Inputs do not have text content. They have a value.
<input id="name" value="Maya">
<script>
const input = document.querySelector("#name");
console.log(input.value); // → Maya
input.value = "Meera";
</script>
Using innerHTML for plain text
el.innerHTML = userName can run code if the name contains HTML. Use textContent for text.