Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between textContent vs innerText

Tags:

javascript

What is the difference between textContent and innerText in JavaScript?

Can I use textContent as follows:

var logo$ = document.getElementsByClassName('logo')[0]; logo$.textContent = "Example"; 
like image 433
J K Avatar asked Feb 04 '16 22:02

J K


People also ask

What is the diff between innerHTML and innerText and textContent?

Additional notes. innerText retrieves and sets the content of the tag as plain text, where innerHTML retrieves and sets the same content in HTML format.

What is the difference between textContent and value?

value is for form elements to get the value of the form element. input. textContent is for other elements to get the content of the element.

What is the difference between innerText and outerText?

Basically, innerText: what's between the tags of the element. outerText: content of the element, including the tags.

What does innerText mean?

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.


1 Answers

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; } 
like image 107
webketje Avatar answered Sep 30 '22 12:09

webketje