Use textContent when a UI needs text, not markup. It reads or replaces the plain text of a DOM node and its descendants. Assigning a string treats it as text rather than parsing it as HTML, making it the straightforward choice for user-generated or external text. section 6.2.7 section 7.6.2
Choose the update method by what the content requires:
- For text, assign textContent—even inside a shadow root. section 6.2.7 section 7.6.2
- For structure, create nodes and insert them with DOM methods. Use innerHTML only for controlled markup; sanitize user-supplied HTML before rendering it. section 6.2.7 section 7.6.2
Add a text heading
const title = document.createElement("h1"); title.textContent = "Hello DOM"; document.body.prepend(title); createElement supplies the structure; textContent supplies its text. section 6.2
const card = document.createElement("article");
card.className = "card";
card.innerHTML = `<h2>Profile</h2><p id="bio"></p>`; //it adds security risks
card.querySelector("#bio").textContent = "Vanilla developer";
document.body.append(card);
The card example sets its bio with textContent. Its innerHTML assignment also shows the boundary: do not substitute unsanitized user input into parsed markup. section 6.2.7
