liveBook · Manning

textContent

As explained in Vanilla Web

textContent is a DOM node property that gets or sets the plain text content of a node and its descendants without parsing markup.

Use textContent when a UI needs text, not markup. It reads or replaces the plain text of a DOM node and its descendants. Assigning a string treats it as text rather than parsing it as HTML, making it the straightforward choice for user-generated or external text. section 6.2.7 section 7.6.2

Choose the update method by what the content requires:

  • For text, assign textContent—even inside a shadow root. section 6.2.7 section 7.6.2
  • For structure, create nodes and insert them with DOM methods. Use innerHTML only for controlled markup; sanitize user-supplied HTML before rendering it. section 6.2.7 section 7.6.2

Add a text heading

const title = document.createElement("h1"); title.textContent = "Hello DOM"; document.body.prepend(title); createElement supplies the structure; textContent supplies its text. section 6.2

const card = document.createElement("article");
card.className = "card";
card.innerHTML = `<h2>Profile</h2><p id="bio"></p>`; //it adds security risks
card.querySelector("#bio").textContent = "Vanilla developer";
document.body.append(card);

The card example sets its bio with textContent. Its innerHTML assignment also shows the boundary: do not substitute unsanitized user input into parsed markup. section 6.2.7

How Vanilla Web covers it

How deep it goes
Defines plain-text assignment and contrasts it with HTML parsing, without detailing browser implementation internals.
Examples
Creates a heading with createElement and fills a profile bio with textContent.
What it assumes
Assumes basic JavaScript access to DOM elements and introduces textContent alongside native element-modification APIs.
What you can do after
Apply it via the native DOM API to render text safely while reserving HTML parsing for controlled or sanitized markup.
How it connects
Connects textContent to innerHTML, DOM node creation, shadow DOM, and cross-site scripting prevention.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.