Differences between innerText and textContent

This free small JavaScript tutorial will overview the differences between innerText and textContent attributes, so you can understand and use them better.


Sampled by © JavaScriptBank.com

I was having an issue with the javascript innerText property today. I was to lazy to convert the legacy code that I was working on to use proper DOM so I did some reading on the issue.

Turns out that FireFox doesn't use innerText at all. Apparently the proper DOM property to use is textContent. textContent does basically the same thing as innerText.

A not so pretty solution to this issue is to check at the start of the script whether the browser supports innerText or textContent. I found a few resources that allowed me to copy and paste a few lines to make everything work.

This one which I found on coderlab is a little bulky but it gets the job done. It checks which property is available and then forces the programmer to check that flag every time he wants to use the property.


var hasInnerText =
(document.getElementsByTagName("body")[0].innerText
 != undefined) ? true : false;
var elem = document.getElementById('id');
if(!hasInnerText){
    elem.textContent = value;
} else{
    elem.innerText = value;
}

This is the method I actually used. I just or'd the two different properties together and it seemed to work. I guess one will always be undefined.


var message = elem.innerText || elem.textContent;

At least FireFox is following the standards unlike Internet Explorer which always needs special css and javascript. Making everything work in Internet Explorer always adds hours onto development time...

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB


Top view articles
Top 10 Beautiful Christmas Countdown Timers
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 10 Best JavaScript eBooks that Beginners should Learn
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com