innerHtml vs innerText

by SelectNt

HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<p id="mainContent">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlWrite"></p>
<p id="textWrite"></p>
<!-- P2 -->
<p id="htmlWrite_encodedChar"></p>
<p id="textWrite_encodedChar"></p>
<!-- P3 @note: -->
<p id="htmlRead_Then_htmlWrite"></p>
<p id="htmlRead_Then_textWrite"></p>
<p id="textRead_Then_htmlWrite"></p>
<p id="textRead_Then_textWrite"></p>
<!-- P4 @note: -->
<p id="mainContent_encodedChar">Make &lt;em&gt;this&lt;/em&gt; problem more <strong>complicated</strong>, if <em>you</em> &lt;em&gt;can&lt;/broken&gt; understand.</p>
<p id="htmlRead_Then_htmlWrite_encodedChar"></p>
<p id="htmlRead_Then_textWrite_encodedChar"></p>
<p id="textRead_Then_htmlWrite_encodedChar"></p>
<p id="textRead_Then_textWrite_encodedChar"></p>
<script src="commentNt.js"></script>
</body>
</html>

JavaScript

/* 
@rule: 
innerHTML
- write: whatever String you write to the `ele.innerHTML`, `ele` (the code of the element in the html file) will be exactly same as it is written in the String.
- read : whatever you read from the `ele.innerHTML` to a String, the String will be exactly same as it is in `ele` (the html file).
+ => `.innerHTML` will **not make any modification** for your read/write

innerText
- write: when you write a String to the `ele.innerText`, any `html reserved special character` in the String will be **encoded** into html format first, then stored into the `ele`. 
  + eg: `<p>` in your String will become `&lt;p&gt;` in the `ele` 
- read : when you read from the `ele.innerText` to a String, 
  1. any `html reserved special character` in the `ele` will be **decoded** back into a readable text format, 
  2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"
      + if there is an invalid `html tag` originally in the `ele` (the html code), `.innerText` 
  3. then stored into the String. 
 */
// >
var alter_ori = window.alert;
window.alert = function() {}; // disable alert -> view the aggregated console.log

// > @basic (simple)
// read
var ele_mainContent = document.getElementById('mainContent');
alert(ele_mainContent.innerHTML); // This is a <strong>sample</strong> sentennce for Reading.
// >" + => `.innerHTML` will **not make any modification** for your read/write
alert(ele_mainContent.innerText); // This is a sample sentennce for Reading.
// >" 2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"

// write
var str_WriteOutput = "Write <strong>this</strong> sentence to the output.";
var ele_htmlWrite = document.getElementById('htmlWrite');
var ele_textWrite = document.getElementById('textWrite');
ele_htmlWrite.innerHTML = str_WriteOutput;
ele_textWrite.innerText = str_WriteOutput;

alert(ele_htmlWrite.innerHTML); // Write <strong>this</strong> sentence to the output.
// >" + =>...