Node.textContent - Web APIs 编辑

The textContent property of the Node interface represents the text content of the node and its descendants.

Note: textContent and HTMLElement.innerText are easily confused, but the two properties are different in important ways.

Syntax

let text = someNode.textContent
someOtherNode.textContent = string

Value

A string or null

Description

The value of textContent depends on the situation:

Setting textContent on a node removes all of the node's children and replaces them with a single text node with the given string value.

Differences from innerText

Don't get confused by the differences between Node.textContent and HTMLElement.innerText. Although the names seem similar, there are important differences:

  • textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows “human-readable” elements.
  • textContent returns every element in the node. In contrast, innerText is aware of styling and won’t return the text of “hidden” elements.
    • Moreover, since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)
  • Unlike textContent, altering innerText in Internet Explorer (version 11 and below) removes child nodes from the element and permanently destroys all descendant text nodes. It is impossible to insert the nodes again into any other element or into the same element after doing so.

Differences from innerHTML

Element.innerHTML returns HTML, as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML.

Moreover, using textContent can prevent XSS attacks.

Examples

Given this HTML fragment:

<div id="divA">This is <span>some</span> text!</div>

... you can use textContent to get the element's text content:

let text = document.getElementById('divA').textContent;
// The text variable is now: 'This is some text!'

... or set the element's text content:

document.getElementById('divA').textContent = 'This text is different!';
// The HTML for divA is now:
// <div id="divA">This text is different!</div>

Specifications

SpecificationStatusComment
DOM
The definition of 'Node.textContent' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:93 次

字数:6695

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文