JS DOM: innerHTML, textContent, innerText, nodeValue

By Xah Lee. Date: . Last updated: .

innerHTML

innerHTML is meant to be HTML code.

// change text content of first p tag
document.getElementsByTagName("p")[0].innerHTML = "<b>water</b>";
// the word is shown as bold

textContent vs innerText

What is the difference between textContent and innerText

ai answer

textContent and innerText both get/set the text of a DOM node (ignoring HTML tags), but they differ significantly in what they include, how they handle styling/visibility, performance, and scope.

Key Differences

Aspect textContent (Node) innerText (HTMLElement)
What it returns All text content of the node and its descendants, including hidden text, <script>, <style>, comments ignored, raw whitespace/line breaks from the markup Approx. the rendered/visible text a user would see (or get by selecting + copying). Ignores hidden elements, normalizes whitespace, respects <br>, and applies some CSS text transformations
CSS / visibility Completely ignores CSS and layout. Includes display: none, visibility: hidden, etc. Aware of CSS styling and computed styles. Skips non-rendered/"human-readable" content
Performance Fast — no layout/reflow needed Slower — reading it can trigger a reflow to get up-to-date styles
Availability All Node types Only HTMLElements
Setting value Replaces all children with a single text node Same, but converts line breaks into <br> elements
Standardization Long-standing DOM standard Originally non-standard (IE); later standardized

Practical Example

<div id="demo">
  <style>p { color: red; }</style>
  Visible text.
  <span style="display: none">Hidden text</span>
  <br>
  More text.
</div>

When to Use Which

Note: Neither parses HTML (unlike innerHTML). Setting either one removes existing child nodes. Both are widely supported in modern browsers.

nodeValue

The most compatible and standard way of setting text content is first to get the element's content as a text node, then set nodeValue, like this:

node.firstChild.nodeValue = text

But, if a element's content is empty, it doesn't have any child (thus no text node), so you need to check if element has firstChild first.

const f_addTextNode = (xel, xtext) => {
 while (xel.firstChild) xel.removeChild(xel.firstChild);
 xel.appendChild(document.createTextNode(xtext));
};

f_addTextNode(document.getElementsByTagName("p")[0], "good");

History

JS DOM, About Node, Node Type

Basic DOM Element Methods