J

JavaScript Handbook

Clean • Professional

DOM HTML (innerHTML, textContent) in JavaScript

1 minute

DOM HTML (innerHTML, textContent)

The DOM HTML allows JavaScript to access, read, and modify the content of HTML elements dynamically. This is a core part of creating interactive and responsive web pages, where the content can change without reloading the page.

1. innerHTML

The innerHTML property is used to get or set the HTML content inside an element. It can include both text and HTML tags, allowing you to insert formatted content or nested elements.

Example:

// Get HTML content
let htmlContent = document.getElementById("demo").innerHTML;

// Set HTML content
document.getElementById("demo").innerHTML = "<strong>Hello World!</strong>";

2. textContent

The textContent property gets or sets only the text content of an element, ignoring HTML tags. It is safer and faster than innerHTML when working with plain text.

Example:

// Get text content
let text = document.getElementById("demo").textContent;

// Set text content
document.getElementById("demo").textContent = "Hello World!";

Difference Between innerHTML and textContent

FeatureinnerHTMLtextContent
Includes HTML tags?YesNo
PerformanceSlightly slowerFaster
Security RiskHigher (XSS)Lower
Best Use CaseAdding formatted contentAdding plain text

Why DOM HTML Matters

  • Enables dynamic updates without reloading the page.
  • Helps create interactive websites (e.g., live content updates, interactive messages, dynamic lists).
  • Allows programmatic content manipulation, improving user experience.
  • Works seamlessly with DOM events to update content based on user actions.

Practical Example

Imagine a website where clicking a button changes a welcome message:

document.getElementById("btn").addEventListener("click", function() {
    document.getElementById("message").innerHTML = "<em>Welcome to our website!</em>";
});

 

Article 0 of 0