iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

PropertyWhat it returns / setsUse when…
textContentConcatenated text of the element and descendants, including hidden elements.Safe text — preferred default.
innerTextRendered text — respects CSS (skips hidden), triggers layout.You need what the user actually sees.
innerHTMLHTML markup inside the element.Inserting trusted markup.
outerHTMLIncluding 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';

Test yourself

Q1. Safer choice for plain user text is…
Q2. Append HTML at the end of an element with…
Q3. `innerText` differs from `textContent` because it…

Discussion

Loading…