JavaScript: innerHTML
The innerHTML property reads or replaces an element’s contents as HTML markup.
What you will learn
- How to read and replace HTML inside an element
- Why innerHTML is different from textContent
- How to avoid inserting untrusted input as markup
Minimal example
const box = document.querySelector('#box');
if (box) box.innerHTML = '<strong>Ready</strong>';The <strong> element is parsed and rendered as bold text. If you only need to display a string, prefer textContent so the value is treated as plain text.
Security rule
Never place user-controlled or otherwise untrusted text directly into innerHTML. It can create a cross-site scripting (XSS) vulnerability. Build trusted markup carefully, or use DOM methods and textContent for plain text.
Common mistakes
- Remember that assigning innerHTML replaces existing child nodes.
- Do not confuse HTML source with visible text.
- Check that the target element exists before updating it.