JAVASCRIPT

Safely Update Element Content: textContent vs innerHTML

Understand the crucial difference between `textContent` and `innerHTML` for updating DOM elements. Use `textContent` for plain text and `innerHTML` for HTML content.

// Assume you have an HTML element:
// <div id="contentArea">Original Content</div>

const contentArea = document.getElementById('contentArea');

// Using textContent: Sets or gets the plain text content of an element.
// HTML tags within the string will be escaped and displayed as text.
if (contentArea) {
  contentArea.textContent = 'Updated with <strong>plain text</strong>.';
  // Output in browser: Updated with <strong>plain text</strong>.

  // Getting plain text content
  const currentText = contentArea.textContent;
  console.log('Current text content:', currentText);
}

// Using innerHTML: Sets or gets the HTML content of an element.
// HTML tags within the string will be parsed and rendered.
if (contentArea) {
  contentArea.innerHTML = 'Updated with <em>HTML</em> content and a <span style="color: red;">red span</span>.';
  // Output in browser: Updated with HTML content and a red span.

  // Getting HTML content
  const currentHTML = contentArea.innerHTML;
  console.log('Current HTML content:', currentHTML);
}

// Caution: Using innerHTML with user-supplied data can lead to XSS vulnerabilities.
// Always sanitize user input before setting it with innerHTML.
// Example of potential danger:
// contentArea.innerHTML = '<img src="x" onerror="alert(\'XSS Attack!\')">'; // Don't do this with untrusted input
How it works: This snippet illustrates the key differences between `textContent` and `innerHTML` for manipulating the content of DOM elements. `textContent` is ideal and safer for inserting plain text, as it automatically escapes any HTML characters. `innerHTML` allows you to inject or retrieve full HTML structures, but it requires careful use, especially with user-supplied data, to prevent Cross-Site Scripting (XSS) vulnerabilities by ensuring proper sanitization.

Need help integrating this into your project?

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

Hire DigitalCodeLabs