JS DOM: textContent, innerHTML, innerText, nodeValue

By Xah Lee. Date: . Last updated: .

What is the difference between textContent, innerHTML, innerText, nodeValue?

innerHTML

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

textContent

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

innerText

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

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.

// change a element's text content, for xml or html

// add a text content xtext to an element xel
// Version: 2022-08-21
const f_addTextNode = ((xel, xtext) => {
  if (xel.firstChild) {
    xel.firstChild.nodeValue = xtext;
  } else {
    xel.appendChild(document.createTextNode(xtext));
  }
});

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

History

JS DOM, About Node, Node Type

JS DOM, Insert, Remove