DOM: textContent, innerHTML, innerText, nodeValue

By Xah Lee. Date: . Last updated: .

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

innerHTML

ele.innerHTML is the most useful, and supported by all browsers back to 2010. innerHTML can be text content or HTML source code.

// innerHTML can be used to insert plain text content or HTML
// this creates a list inside a div element

const ele = document.getElementsByTagName("div");

ele[0].innerHTML =  `<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>`;

textContent

ele.textContent is in standard's spec around 2011, and is supported by browsers since about 2013. textContent's value is meant to be text only, not HTML. It is not style aware.

// change text content of first p tag
document.getElementsByTagName("p")[0].textContent = "I <b>love</b> JS";
// the bolded text won't be rendered in bold. Firefox, Chrome 2015-03

innerText

ele.innerText is originall from Microsoft Internet Explorer, but is now in html spec. It's not supported by Firefox as of 2015-03-13.

nodeValue

nodeValue is for setting content of text node only. [see get Node Name (Element Tag Name), Node Type, Node Value] It is particularly useful when working with XML, such as SVG. [see Practical SVG Tutorial]

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 xele
// version 2022-08-21
const f_addTextNode = ((xele, xtext) => {
  if (xele.firstChild) {
    xele.firstChild.nodeValue = xtext;
  } else {
    xele.appendChild(document.createTextNode(xtext));
  }
});

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

JavaScript/DOM: Node Name, Node Type, Node Value

BUY Ξ£JS JavaScript in Depth