Skip to content

JavaScript Tutorial The DOM

Changing Text and HTML with JavaScript

Lesson 102 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Once you have an element, you can change what it shows.

textContent

Sets or reads the plain text inside an element.

index.html
HTML
<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.

index.html
HTML
<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

PropertyReadsWritesSafe for user text
textContentall text, including hiddentextYes
innerTextvisible text onlytextYes
innerHTMLthe HTML sourceHTML (parsed)No

Building a list

index.html
HTML
<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

script.js
JS
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.

index.html
HTML
<input id="name" value="Maya">
<script>
  const input = document.querySelector("#name");
  console.log(input.value);   // → Maya
  input.value = "Meera";
</script>
warning
Using innerHTML for plain text
el.innerHTML = userName can run code if the name contains HTML. Use textContent for text.