← Back to all snippets
JAVASCRIPT

Safely Update Element Text Content

Learn to update the visible text content of any HTML element using the `textContent` property in JavaScript, preventing XSS vulnerabilities compared to `innerHTML`.

const myHeading = document.getElementById('mainHeading');
if (myHeading) {
  myHeading.textContent = 'Welcome to Our New Page!';
}

const statusMessage = document.querySelector('.status-box');
if (statusMessage) {
  statusMessage.textContent = 'Operation completed successfully at ' + new Date().toLocaleTimeString();
}
How it works: This snippet demonstrates updating the visible text content of an HTML element using the `textContent` property. This method is generally safer than `innerHTML` when dealing with user-generated or external text, as it automatically escapes HTML, preventing potential Cross-Site Scripting (XSS) attacks by treating all input as plain text.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs