JS DOM: Change Element Content
Adding HTML or XML
// HTML content el.innerHTML = "<b>bold</b>";
Adding 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="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
- JS DOM: Node, Node Type, Element
- JS DOM: Get Element by ID, Name, Class etc
- JS DOM: Get Current Script Element
- JS DOM: Get Parent, Child, Sibling
- JS DOM: NodeList vs HTMLCollection
- JS DOM: Iterate HTMLCollection
- JS DOM: Element Attribute Methods
- JS DOM: Class Attribute (get add remove toggle)
- JS DOM: Create Element, Clone
- JS DOM: Insert, Remove, Replace Element
- JS DOM: insert Adjacent Element
- JS DOM: appendChild
- JS DOM: innerHTML, textContent, innerText, nodeValue
- JS DOM: Remove Element
- JS DOM: Remove All Children
- JS DOM: Change Element Content
- JS DOM: Add, Remove Event Handler