Change Text Using JavaScript innerHTML

How can I change a text with JavaScript innerHTML?
This is my example:
I have the following text:

Most programmers live on coffee.

I want to add to this text: and chocolate So the new text should look like:

Most programmers live on coffee and chocolate.

Hi @icxc !

You can use the += operator to add on the new text.

<p id="text">Most programmers live on coffee</p>
const text = document.getElementById("text");

text.innerHTML += " and chocolate.";
1 Like

and const text, I think there are not the same. What if I choose, for example:

? I will have text.innerHTML or p1.innerHTML?

You can choose whatever variable and id names you want.

I just wrote a quick example to show you the basics of how it works.

I will rephrase:
id=β€œtext” and const text, I think are not the same.
What if I choose, for example: p id=β€œp1”?
Will I have text.innerHTML or p1.innerHTML?

In that case then you could write it like this.

<p id="p1">Most programmers live on coffee</p>
const paraText = document.getElementById("p1");

paraText.innerHTML += " and chocolate.";

Hope that is clearer

Thanks Jessica for your help.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.