JS DOM: Change Element Content

By Xah Lee. Date: . Last updated: .

Change element's content

Set html/xml to content

if the content you want to change to is html or xml, use innerHTML.

// HTML content
el.innerHTML = "<b>bold</b>";

Set plain text to content

if the content you want to change to is text, use textContent.

el.textContent = "new text";

Example.

Press the following buttons to change the paragraph.

How are you?

Code

<p id="root_bFc4N">How are you?</p>
<button id="btn1" type="button">Answer</button>
<button id="btn2" type="button">Question</button>
"use strict";
const root = document.getElementById("root_bFc4N");
if (!root)
    throw (new Error(`#root_bFc4N not found.`));
const btn1 = document.getElementById("btn1");
if (!btn1)
    throw (new Error(`#btn1 not found.`));
const btn2 = document.getElementById("btn2");
if (!btn2)
    throw (new Error(`#btn1 not found.`));
const f1 = () => {
    root.innerHTML = "Fine, thank you.";
};
const f2 = () => {
    root.innerHTML = "How are you?";
};
btn1.addEventListener("click", f1);
btn2.addEventListener("click", f2);