Clean β’ Professional
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.
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>";
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!";
| Feature | innerHTML | textContent |
|---|---|---|
| Includes HTML tags? | Yes | No |
| Performance | Slightly slower | Faster |
| Security Risk | Higher (XSS) | Lower |
| Best Use Case | Adding formatted content | Adding plain text |
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>";
});Β