DOM HTML
JavaScript reads and writes the HTML content of elements with a few well-named (and a few badly-named) properties.
The three flavours
| Property | What it returns / sets | Use when… |
|---|---|---|
textContent | Concatenated text of the element and descendants, including hidden elements. | Safe text — preferred default. |
innerText | Rendered text — respects CSS (skips hidden), triggers layout. | You need what the user actually sees. |
innerHTML | HTML markup inside the element. | Inserting trusted markup. |
outerHTML | Including the element itself. | Replacing an element entirely. |
insertAdjacentHTML positions
JS
// "beforebegin" — before the element itself
// "afterbegin" — first child
// "beforeend" — last child
// "afterend" — after the element
list.insertAdjacentHTML("beforeend", `<li>New</li>`);
Safe text vs. trusted HTML
JS
const userInput = "<img src=x onerror=alert(1)>"; el.textContent = userInput; // ✓ harmless — appears as text el.innerHTML = userInput; // ✗ XSS — onerror fires
Security: Treat any HTML you assemble from user input as untrusted. Sanitise it (e.g. with DOMPurify) or use
textContent for the parts that came from outside.Tip: Setting
innerHTML replaces every child of the element — including their event listeners. If you only need to add one item, insertAdjacentHTML avoids that work.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from DOM HTML!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Safely set the heading text — no HTML parsing.
h1.
= 'Welcome';
Eleven letters.
Discussion
Loading…