Although the results will be similar in some cases, they will not be the same at all (as indicated by Asier in his answer ). Now, there are more differences than just those indicated there.
I will take the opportunity to introduce two more that do not appear in the question, but which are relevant to this case: .textContent
and .innerText
(there is a .outerText
but is not standard).
So that each of them works:
-
.innerHTML
returns text and code (in the form of text), that is, it will return the labels and the text contained in them.
-
.innerText
returns only the rendered text. The key part is "rendering". That means that only the text that the browser can display will be displayed (ie if there is a script
the code inside will not be displayed as text).
-
.textContent
returns only the text. And it is important to identify that by text in this case we refer to all the content text (eg if there is a script
, the code will be displayed as text even if it is not visible on the page).
-
.text
works as a short read-only version of .textContent
... although the "read only" is not something that browsers impose. In addition, its behavior will change depending on the element in which it is used and is considered obsolete for some elements .
We are going to see an example with these four functions in the body
element (one of those that differs and that is considered obsolete from HTML 5 ):
var miBody = document.getElementById("miBody");
console.log(miBody.innerHTML);
console.log(miBody.textContent);
console.log(miBody.text);
console.log(miBody.innerText);
<body id="miBody">
<a href="miA" href="http://es.stackoverflow.com">Soy un enlace</a>
<script id="miScript">
var variable = 1;
</script>
Texto suelto
</body>
Why does it return an empty string for .text
? Interesting fact: in previous versions of HTML, the attribute text
in body
was used to change the color of the source, although that functionality is considered obsolete for years, browsers still use it. For example, if you make miBody.text = "#ff0000";
you would expect the text of the page to change to # ff0000, right? Do not! The color of the text will change to red:
var miBody = document.getElementById("miBody");
miBody.text = "#ff0000";
<body id="miBody">
<a href="miA" href="http://es.stackoverflow.com">Soy un enlace</a>
<script id="miScript">
var variable = 1;
</script>
Texto suelto
</body>
It is an example of an attribute that should work in one way, but browsers use it in a different way. Instead of using .text
you should use .innerText
or .textContent
, which are standard and supported by all modern browsers.