How to replace the text of an element with another text?

Asked

Viewed 1,283 times

1

I want to exchange the text of one element for 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 the elementoTexto = elementoTexto + " texto." cannot exchange text from <p id="elemento">isto é um</p> for <p id="elemento">isto é um texto.</p>.

2 answers

2

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

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 comments that adjusts agent

  • It worked, it was pretty simple huh. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.