DOM: Change Element's Content

By Xah Lee. Date: . Last updated: .

This page shows a example of how to change a HTML page's content with JavaScript.

Press the following buttons to change the paragraph.

How are you?

Here's the HTML code.

<p id="showBox87134">How are you?</p>
<button id="btn1" type="button">Answer</button>
<button id="btn2" type="button">Question</button>

Here's the JavaScript code.

const showBox87134 = document. getElementById("showBox87134");
const btn1 = document. getElementById ('btn1');
const btn2 = document. getElementById ('btn2');

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

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

Note: if you just want to insert text that's not HTML, best to use node.textContent = string

[see DOM: Difference Between textContent, innerHTML, innerText, nodeValue]

DOM How-To


Web Scripting Overview


HTML Input


Web Scripting Examples


Web Scripting Misc


jQuery


node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials