JS DOM: Change Element Content

By Xah Lee. Date: . Last updated: .

How to Change Element's Content

There are 3 ways to change a element's content.

Example

Press the following buttons to change the paragraph.

How are you?

Code

<p id="root865">How are you?</p>
<button id="btn1" type="button">Answer</button>
<button id="btn2" type="button">Question</button>
const root865 = document.getElementById("root865");
const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");

const f1 = () => {
  root865.innerHTML = "Fine, thank you.";
};
const f2 = () => {
  root865.innerHTML = "How are you?";
};

btn1.addEventListener("click", f1, false);
btn2.addEventListener("click", f2, false);

Basic DOM Element Methods