JavaScript: How to Change Element's Content

, , …,

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="id57512">How are you?</p>
<button id="b1">Answer</button>
<button id="b2">Question</button>

Here's the JavaScript code.

function f1() {document.getElementById("id57512").textContent="Fine, thank you.";}
function f2() {document.getElementById("id57512").textContent="How are you?";}

//define the behavior
document.getElementById("b1").addEventListener("click", f1 , false);
document.getElementById("b2").addEventListener("click", f2 , false);

Note: textContent is only supported by all browsers around 2012. For alternative, see: JavaScript: What's the difference between textContent, innerHTML, innerText, nodeValue?

Like what you read? Please tell friends, share link, or Buy JavaScript in Depth. Thanks.
blog comments powered by Disqus