Difference between textContent vs innerText

The key differences between innerText and textContent are outlined very well in Kelly Norton’s blogpost: innerText vs. textContent. Below you can find a summary:

  1. innerText was non-standard, textContent was standardized earlier.
  2. innerText returns the visible text contained in a node, while textContent returns the full text. For example, on the following HTML <span>Hello <span style="display: none;">World</span></span>, innerText will return ‘Hello’, while textContent will return ‘Hello World’. For a more complete list of differences, see the table at http://perfectionkills.com/the-poor-misunderstood-innerText/ (further reading at ‘innerText’ works in IE, but not in Firefox).
  3. As a result, innerText is much more performance-heavy: it requires layout information to return the result.
  4. innerText is defined only for HTMLElement objects, while textContent is defined for all Node objects.

Be sure to also have a look at the informative comments below this answer.

textContent was unavailable in IE8-, and a bare-metal polyfill would have looked like a recursive function using nodeValue on all childNodes of the specified node:

function textContent(rootNode) {
  if ('textContent' in document.createTextNode(''))
    return rootNode.textContent;

  var childNodes = rootNode.childNodes,
      len = childNodes.length,
      result="";
  
  for (var i = 0; i < len; i++) {
    if (childNodes[i].nodeType === 3)
      result += childNodes[i].nodeValue;
    else if (childNodes[i].nodeType === 1) 
      result += textContent(childNodes[i]);
  }

  return result;
}

Leave a Comment