It's the same logic as the colleague code @MagicHat, I'm just showing an alternative syntax and using innerText
:
document.getElementById("elemento").innerText += " texto";
<p id="elemento">isto é um</p>
Understanding your code problem:
When you did this:
var elementoTexto = document.getElementById("elemento").innerHTML
You simply saved the element's HTML to a elementoTexto
variable, and then:
elementoTexto = elementoTexto + " texto."
added texto
to this variable. But it did not change the element. Here's 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 saving your content . So when we change the innerHTML
property, we're changing within the fact element, not just a copy of its value.
Note that as a general rule this type of construction
elementoTexto.innerHTML = elementoTexto.innerHTML + " texto.";
can be written in a shorter way
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