DOM: Difference Between textContent, innerHTML, innerText, nodeValue

By Xah Lee. Date: . Last updated: .

What's 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>`;

nodeValue

nodeValue is for setting content of text node only.

[see DOM: Node Type, Node Name, Node Value]

nodeValue is particular 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:

ele.firstChild.nodeValue = "…"

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.

// the most compatible way to change a element's text content.

const addTextNode = ((ele, text) => {
    if ( ele.firstChild ) {
        ele.firstChild.nodeValue = text;
    } else {
        ele.appendChild(document.createTextNode(text));
    }
});

const myEle = document.getElementsByTagName("p")[0];

const newText = "hi";

addTextNode( myEle, newText );

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 from Internet Explorer. It's not supported by Firefox as of .

DOM How-To

  1. DOM: Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. Remove Element's Attribute Value
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. DOM: Navigate DOM Tree
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc