Difference between using innerText and textContent depending on styles applied to outer element
innerHTML and textContent read from the actual content of the element whereas innerText will apply display styles to the result before returning. Note that the first item in the innerText result is empty whereas the first textContent and first innerHTML both still have the actual value.
by steveukx
HTML
<p>Tests the result of using innerText on an element based on any styling applied to it.</p>
<p>innerText values</p>
<div id="innerText"></div>
<p>textContent values</p>
<div id="textContent"></div>
<p>innerHTML values</p>
<div id="innerHTML"></div>
<p>Source Elements</p>
<div id="source"></div>
CSS
#source {
padding-bottom: 1em;
margin-bottom: 1em;
border-bottom: 1px solid #333;
}
#source .itm-0 { visibility: hidden; }
#source .itm-1 { display: none; }
#source .itm-2 {
font-size: 0; text-indent: -1000px; }
.itm-0 { background: #F33; }
.itm-1 { background: #090; }
.itm-2 { background: #69F; }
.itm-3 { background: #F90; }
#source > div, output {
display: block;
height: 20pt;
margin-bottom: 5pt;
text-align: center;
color: #EEE;
}
html {
font: 10pt/2 "Lucida Sans Unicode", "Sans-Serif";
}
JavaScript
if(![].forEach) { // IE8 doesn't have forEach
Array.prototype.forEach = function(fn,sc) {
for(var i=0,l=this.length;i<l;i++)
fn.call(sc||window,this[i],i,this);
};
}
var source = document.getElementById('source');
String(new Array(4)).split(',').forEach(function(a,i) {
var cls = " class='itm-" + i + "'";
source.insertAdjacentHTML('beforeEnd',
'<div' + cls + '>some content</div>');
});
['innerText', 'textContent', 'innerHTML']
.forEach(function(id) {
var el,output = document.getElementById(id);
[].forEach.call(
source.querySelectorAll('div'),
function(div, index) {
el = output.appendChild(
document.createElement('output'));
el.innerHTML = div[id];
el.className = 'itm-' + index;
});
});
// classes rather than CSS3 to allow for testing in IE8