OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 18

Modifying DOM Elements: textContent, innerHTML, Attributes, and Styles

By Ratan Updated: 16 Oct 2026

Dynamically change text, HTML structure, classes, styles, and attributes of elements.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Change the right property for the job

Use textContent for plain text. Use attributes or DOM properties for structured element state. Use classes for reusable styling. innerHTML parses markup, so inserting untrusted text through it can create cross-site scripting vulnerabilities.

Waiting

The status is plain text; the class can supply its appearance from CSS. disabled is a boolean DOM property. Setting the HTML disabled attribute to the text 'false' does not enable a control, because presence of the boolean attribute represents true.

Safe text versus parsed markup

const entered = 'Student note';
status.textContent = entered; // displays the literal tag characters
// status.innerHTML = entered; // parses markup; unsafe for untrusted input

If rich HTML is genuinely required, use a reviewed sanitization strategy and appropriate security controls. Escaping rules depend on context; a string safe for text is not automatically safe as a URL, style or script.

Classes and inline styles

status.classList.toggle('is-error', false);
status.style.marginTop = '1rem';

classList can add, remove, toggle or test class tokens without replacing unrelated classes. Inline styles suit specific dynamic values, but shared visual states are easier to maintain in a stylesheet. Replacing className wholesale can accidentally remove another component's class.

Attribute/property differences

Attributes generally describe markup/defaults; DOM properties can reflect current state. An input's value property changes as the user types, while its value attribute can still describe the initial default. Use the API corresponding to the state you intend to read or change.

Practice

  1. Display a user's note containing angle brackets as literal text.
  2. Toggle an error class without removing the base status class.
  3. Disable and enable the Save button through its property.
  4. Explain why setting disabled='false' still leaves an HTML control disabled.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat