Both innerText and innerHtml are text messages between print labels
1. innerText prints plain text information between tags, which filters out the tags. Low versions of Firefox browser do not support textContent.
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Document</title>
- </head>
- <body>
- <div id="box">
- <p>This is P Label</p>
- <p>This is P Label</p>
- <p>This is P Label</p>
- </div>
- </body>
- <script>
- var box = document.getElementById("box");
- //Printing plain text information between labels will filter out the labels.
- var str = box.innerText;
- console.log(str);
- </script>
- </html>
Print results
- This is the P label.
- This is the P label.
- This is the P label.
2. innerHtml prints the contents between tags, including tags and text information, which are supported by all browsers, but older browsers print as is
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Document</title>
- </head>
- <body>
- <div id="box">
- <p>This is P Label</p>
- <p>This is P Label</p>
- <p>This is P Label</p>
- </div>
- </body>
- <script>
- var box = document.getElementById("box");
- //Print content between labels, including labels and text information
- var str = box.innerHTML;
- console.log(str);
- </script>
- </html>
Print results
- <p>This is label P</p>.
- <p>This is label P</p>.
- <p>This is label P</p>.
If the p label in the div is not wrapped, the printed result will be output as is
- <div id="box">
- < p > This is the P label </p>.
- <p>This is the P label</p><p>This is the P label</p>.
- </div>
Print results
- <p>This is label P</p>.
- <p>This is label P</p><p>This is label P</p>.
However, it is compatible to use innerText. Lower versions of Firefox browser do not support it, but rather textContent, so we need to encapsulate a compatible version and call methods
- <pre class="html" name="code">//Objects to get labels
- var box = document.getElementById("box");
- //Call Method
- var str = getText(box);
- console.log(str);
- /**
- * Encapsulates a version function to get text information compatibility between tags.
- * @param element Label object
- * @returns {*}
- */
- function getText(element) {
- if(element.innerText) {
- return element.innerText; //IE8 and previous browser support, now both.
- }else {
- return element.textContent; //Low version of Firefox support
- }
- }