JS DOM: Change Element Content
Add html or xml
// HTML content el.innerHTML = "<b>bold</b>";
Add plain text
// Preferred for plain text (works in HTML and XML) el.textContent = "new text"; // Or the older alternative to textContent (still works) el.innerText = "plain text";
// Or the low-level DOM way (also general) while (el.firstChild) el.removeChild(el.firstChild); el.appendChild(document.createTextNode("new text"));
Example. using innerhtml
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>
const root_bFc4N = document.getElementById("root_bFc4N"); const btn1 = document.getElementById("btn1"); const btn2 = document.getElementById("btn2"); const f1 = () => { root_bFc4N.innerHTML = "Fine, thank you."; }; const f2 = () => { root_bFc4N.innerHTML = "How are you?"; }; btn1.addEventListener("click", f1); btn2.addEventListener("click", f2);