Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

innerText/textContent vs. retrieving each text node [duplicate]

Tags:

javascript

dom

I've heard that using el.innerText||el.textContent can yield unreliable results, and that's why I've always insisted on using the following function in the past:

function getText(node) {      if (node.nodeType === 3) {         return node.data;     }      var txt = '';      if (node = node.firstChild) do {         txt += getText(node);     } while (node = node.nextSibling);      return txt;  } 

This function goes through all nodes within an element and gathers the text of all text nodes, and text within descendants:

E.g.

<div id="x">foo <em>foo...</em> foo</div> 

Result:

getText(document.getElementById('x')); // => "foo foo... foo" 

I'm quite sure there are issues with using innerText and textContent, but I've not been able to find a definitive list anywhere and I am starting to wonder if it's just hearsay.

Can anyone offer any information about the possibly lacking reliability of textContent/innerText?

EDIT: Found this great answer by Kangax -- 'innerText' works in IE, but not in Firefox

like image 611
James Avatar asked Apr 16 '10 14:04

James


People also ask

What is difference between innerText and textContent?

textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements.

Is textContent faster than innerHTML?

Note: Unlike innerHTML, textContent has better performance because its value is not parsed as HTML. For that reason, using textContent can also prevent Cross-Site Scripting (XSS) attacks. Unlike innerText, textContent isn't aware of CSS styling and will not trigger a reflow.

What is the difference between textContent and innerText and innerHTML?

textContents is all text contained by an element and all its children that are for formatting purposes only. innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.

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.


1 Answers

It's all about endlines and whitespace - browsers are very inconsistent in this regard, especially so in Internet Explorer. Doing the traversal is a sure-fire way to get identical results in all browsers.

like image 118
John Resig Avatar answered Sep 29 '22 04:09

John Resig