It’s the same logic as the code of colleague @Magichat, I’m just showing an alternative syntax and the use of innerText
:
document.getElementById("elemento").innerText += " texto";
<p id="elemento">isto é um</p>
Understanding the problem of your code:
When you did it:
var elementoTexto = document.getElementById("elemento").innerHTML
simply saved the widget’s HTML into a variable elementoTexto
, and then:
elementoTexto = elementoTexto + " texto."
added texto
in this variable. But you did not modify the element. See how a small adjustment changes everything:
var elementoTexto = document.getElementById("elemento")
elementoTexto.innerHTML = elementoTexto.innerHTML + " texto."
<p id="elemento">isto é um</p>
In this case, we’re saving the element in elementoTexto
, instead of just keeping its content. So when we move the property innerHTML
, we are changing within the element of fact, not just a copy of its value.
It is worth noting that, as a general rule, this type of construction
elementoTexto.innerHTML = elementoTexto.innerHTML + " texto.";
can be written shorter
elementoTexto.innerHTML += " texto.";
Other examples of syntax simplification:
var x = 100;
x /= 2; // 50 é o mesmo que x = x / 2;
var j = 10;
j *= 10; // 100 é o mesmo que j = j * 10;
var n = 7;
n += 2; // 9 é o mesmo que n = n + 2;
var i = 1;
i++; // 2 é o mesmo que i = i + 1;
var p = 9;
p--; // 8 é o mesmo que p = p - 1
It worked, it was pretty simple huh. Thank you very much
– FireBlast