What is the difference when using .text
and .innerHTML
getting the text?
window.addEventListener('DOMContentLoaded',() => {
var pattern = /^joya[0-9]/,
getting = document.getElementsByTagName('*'),
elements = [];
Array.from(getting).forEach(clase => {
if(pattern.test(clase.className)) elements.push(clase);
});
/* Mostrar */
elements.forEach(i => { /* .text */
console.log('Con .text: ' + i.text);
});
elements.forEach(i => { /* .innerHTML */
console.log('Con innerHTML: ' + i.innerHTML);
});
});
<a class='joya1' href='' value="joyita1">joyyy1</a>
<a class='joya2' href='' value="joyita2">joyyy2</a>
<a class='joya3' href='' value="joyita3">joyyy3</a>
In one case it returns the text that is displayed (
text
) and in the other the HTML code (innerHTML
).In your example they match, but if you modify it a bit you will see the difference:
Although the results will be similar in some cases, they will not be in all (as Asier indicates in his answer ). Now, there are more differences than just the ones listed there.
I am going to take this opportunity to introduce two more that do not appear in the question, but are relevant to this case:
.textContent
e.innerText
(there is one.outerText
but it is not standard).What each of them works for:
.innerHTML
it 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". This means that only the text that the browser can display will be displayed (eg if there is ascript
code inside it will not be displayed as text)..textContent
returns only the text. And it is important to identify that by text in this case we mean all the contained text (eg if there is ascript
, 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 "read-only" is not something that browsers enforce. Also, its behavior will change depending on the element it is used on and is considered deprecated for some elements .Let's see an example with those four functions in the element
body
(one of which differs and is considered deprecated since HTML 5 ):Why does it return an empty string for
.text
? Interesting fact: In earlier versions of HTML, the attributetext
onbody
was used to change the font color, although that functionality has been deprecated for years, browsers still use it. For example, if you do youmiBody.text = "#ff0000";
would expect the page text to change to #ff0000, right? Nope! The text color will change to red:It's an example of an attribute that should work one way, but is used in a different way by browsers. Instead of using
.text
you should use.innerText
or.textContent
, which are standard and supported by all modern browsers.