The innerText
can be understood as:
A property that represents the "rendered" textual content of
a knot and its descendants. Used as getter, it returns
approximate the text that the user would get if he had selected the
content and copied to clipboard
Already innerHTML
:
define or get the HTML syntax describing the descending elements.
So, in simple words, innerText
retrieves and sets the content of the tag as plain text, while innerHTML
retrieves and sets the content in HTML format.
See an example where we get the HTML contents of <div id"innerHTML">
:
let innerHTML = document.getElementById('innerHTML').innerHTML;
console.log(innerHTML);
<div id="innerHTML">Texto <span>Mais texto</span></div>
Now look at this example with innerText
, where we only get the text, without the span
tag, differently from the first example:
let innerText = document.getElementById('innerText').innerText;
console.log(innerText);
<div id="innerText">Texto <span>Mais texto</span></div>
Taking a hook in your question example, if you want to change, for example, the text of a link could use innerText
. See:
var p = document.getElementById("link");
p.innerText="Texto Qualquer";
<p id="p1">I also wrote a book! Read it
<a id="link" href="http://eloquentjavascript.net">here</a>.
</p>
If you wanted to change the HTML content of a div
, or even change the link of a certain element, you could do it with innerHTML
.
var p = document.getElementById("p1");
p.innerHTML='<a href="https://pt.stackoverflow.com/questions/329975/innerhtml-vs-innertext">Trocamos o link</a>';
<p id="p1">I also wrote a book! Read it
.
</p>
References: