The innerText
can be understood as:
a property representing the "rendered" text content of
a node and its descendants. Used as getter, returns
approximate the text the user would get if he had selected the
content and copied to the clipboard
Already the innerHTML
:
defines or obtains the HTML syntax describing the descending elements.
Therefore, in simple words, the innerText
recovers and defines the content of the tag as plain text, while innerHTML
recovers and defines content in HTML format.
Here’s an example of where we get the HTML content from <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 other example with innerText
, where we only get the text, without the tag span
, unlike 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 exchange, for example, the text of a link could use the innerText
. Behold:
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 exchange the HTML content of a div
, or even change the link of a certain element could do it with the innerHTML
.
var p = document.getElementById("p1");
p.innerHTML='<a href="/questions/329975/innerhtml-vs-innertext">Trocamos o link</a>';
<p id="p1">I also wrote a book! Read it
.
</p>
References:
The problem is that using one or the other link
<a>
go away.– Sam