How to change the text of an element by it plus another text?

1

I want to change the text of an element for it plus another text. This is a representation of my code:

Javascript:

var elementoTexto = document.getElementById("elemento").innerHTML
elementoTexto = elementoTexto + " texto."

HTML:

<p id="elemento">isto é um</p>

For some reason elementoTexto = elementoTexto + " texto." can not change the text from <p id="elemento">isto é um</p> to <p id="elemento">isto é um texto.</p> .

    
asked by anonymous 16.07.2016 / 02:47

2 answers

1

It may be so

<p id="elemento">isto é um</p>
<script>
  var elementoTexto = document.getElementById("elemento").innerHTML
 document.getElementById("elemento").innerHTML =  elementoTexto + " texto."
</script>

Anything says agent adjusts

    
16.07.2016 / 02:51
2

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
    
16.07.2016 / 03:25