Enjoy 20% off all plans by following us on social media. Check out other promotions!
测验题

What is the difference between `innerHTML` and `textContent`?

Topics
JAVASCRIPTHTML
在GitHub上编辑

TL;DR

innerHTML and textContent are both properties used to get or set the content of an HTML element, but they serve different purposes. innerHTML returns or sets the HTML markup contained within the element, which means it can parse and render HTML tags. On the other hand, textContent returns or sets the text content of the element, ignoring any HTML tags and rendering them as plain text.

// Example of innerHTML
element.innerHTML = '<strong>Bold Text</strong>'; // Renders as bold text
// Example of textContent
element.textContent = '<strong>Bold Text</strong>'; // Renders as plain text: <strong>Bold Text</strong>

Difference between innerHTML and textContent

innerHTML

innerHTML is a property that allows you to get or set the HTML markup contained within an element. It can parse and render HTML tags, making it useful for dynamically updating the structure of a webpage.

Example

const element = document.getElementById('example');
element.innerHTML = '<strong>Bold Text</strong>'; // This will render as bold text

Use cases

  • Dynamically adding or updating HTML content
  • Rendering HTML tags and elements

Security considerations

Using innerHTML can expose your application to Cross-Site Scripting (XSS) attacks if you insert untrusted content. Always sanitize any user input before setting it as innerHTML.

textContent

textContent is a property that allows you to get or set the text content of an element. It ignores any HTML tags and renders them as plain text, making it safer for inserting user-generated content.

Example

const element = document.getElementById('example');
element.textContent = '<strong>Bold Text</strong>'; // This will render as plain text: <strong>Bold Text</strong>

Use cases

  • Safely inserting user-generated content
  • Stripping HTML tags from a string

Performance considerations

textContent is generally faster than innerHTML because it does not parse and render HTML tags. It simply updates the text content of the element.

Further reading

在GitHub上编辑