Skip to content

Instantly share code, notes, and snippets.

@jrrio
Last active April 23, 2018 23:17
Show Gist options
  • Save jrrio/1d325f7351e18e6aee4bbe8b038139a0 to your computer and use it in GitHub Desktop.
Save jrrio/1d325f7351e18e6aee4bbe8b038139a0 to your computer and use it in GitHub Desktop.
Difference between innerText and textContent

Difference between innerText and textContent

The differences between innerText and textContent methods are outlined in this Stack Overflow article.

  • innerText -> implemented in IE8 and earlier. So innerText is probably not what you want.
  • textContent -> DOM Level 3 - IE9 and W3C standards compliant browsers.
  • Google Chrome implements both innerText and textContent.

Let's define a getElementText() method at load-time in order to use either textContent (preferably) or innerText depending on the browser running this code. This function will also trim the text.

  var getElementText = (function () {
    var parseEl = document.createElement('div');
    if (typeof parseEl.textContent != 'undefined') {
      return function (el) {
        return (el.textContent).replace(/^\s+|\s+$/g, '');
      };
    } else if (typeof parseEl.innerText != 'undefined') { // IE8 and earlier.
      return function (el) {
        return (el.innerText).replace(/^\s+|\s+$/g, '');
      };
    }
  }());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment