← Back to all snippets
JAVASCRIPT

Update Element Text or HTML Content

Discover how to efficiently update the plain text or inner HTML content of an existing DOM element using JavaScript's `textContent` and `innerHTML` properties.

const targetElement = document.getElementById('contentToUpdate');

if (targetElement) {
  // To update with plain text, safer against XSS
  targetElement.textContent = 'New plain text content loaded!';

  // To update with HTML structure, use with caution for security
  // targetElement.innerHTML = '<strong>New HTML content!</strong><br><em>From JavaScript.</em>';
}
How it works: This code illustrates how to retrieve an existing DOM element by its ID and then modify its content. Using `textContent` updates the element with plain text, making it safer by automatically escaping any HTML. Conversely, `innerHTML` allows you to inject or update HTML structures directly, which offers more flexibility but requires careful handling to prevent Cross-Site Scripting (XSS) vulnerabilities if the content comes from untrusted sources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs