JS: Change Element Content
How to Change Element's Content
There are 3 ways to change a element's content.
- Treat it as a innerHTML, and use property
innerHTML
. This is for HTML (not XML), works in all browsers. - Treat it as a text content, and use property
textContent
. This works well if the content is text and contains no HTML. (if you set value to"<b>bold text</b>"
, the text won't be bold.) - Treat it as a DOM tree node, and use property
nodeValue
. This is the most general, and works with XML too.
Example
Press the following buttons to change the paragraph.
How are you?
Here is 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 is 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
Basic DOM Element Methods
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Get Element Parent, Child, Sibling
- DOM: NodeList vs HTMLCollection
- JS: Iterate HTMLCollection
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element Content
- JS: Add, Remove Event Handler