此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Node.textContent
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Node 接口的textContent 属性表示一个节点及其后代的文本内容。
备注:textContent 和HTMLElement.innerText 容易混淆,但这两个属性在重要方面有不同之处 。
In this article
值
一个字符串或null.
描述
textContent 的值取决于具体情况:
如果节点是一个
document,或者一个DOCTYPE ,则textContent返回null。备注:如果你要获取整个文档的文本以及CDATA data ,可以使用
document.documentElement.textContent。如果节点是个CDATA section、注释、processing instruction 或者text node,
textContent返回节点内部的文本内容,例如Node.nodeValue。对于其他节点类型,
textContent将所有子节点的textContent合并后返回,除了注释和 processing instructions。(如果该节点没有子节点的话,返回一个空字符串。)
在节点上设置textContent 属性的话,会删除它的所有子节点,并替换为一个具有给定值的文本节点。
与innerText 的区别
不要对Node.textContent 和HTMLElement.innerText 之间的差异感到困惑。虽然名字看起来很相似,但有重要的不同之处:
textContent会获取所有元素的内容,包括<script>和<style>元素,然而innerText只展示给人看的元素。textContent会返回节点中的每一个元素。相反,innerText受 CSS 样式的影响,并且不会返回隐藏元素的文本,- 此外,由于
innerText受 CSS 样式的影响,它会触发回流(reflow )去确保是最新的计算样式。(回流在计算上可能会非常昂贵,因此应尽可能避免。)
- 此外,由于
与
textContent不同的是,在 Internet Explorer (小于和等于 11 的版本) 中对innerText进行修改,不仅会移除当前元素的子节点,而且还会永久性地破坏所有后代文本节点。在之后不可能再次将节点再次插入到任何其他元素或同一元素中。
与innerHTML 的区别
正如其名称,Element.innerHTML 返回 HTML。通常,为了在元素中检索或写入文本,人们使用innerHTML。但是,textContent 通常具有更好的性能,因为文本不会被解析为 HTML。
此外,使用textContent 可以防止XSS 攻击。
示例
给出这个 HTML 片段:
<div>This is <span>some</span> text!</div>你可以使用textContent 去获取该元素的文本内容:
let text = document.getElementById("divA").textContent;// The text variable is now: 'This is some text!'或者设置元素的文字内容:
document.getElementById("divA").textContent = "This text is different!";// The HTML for divA is now:// <div>This text is different!</div>IE8 的替代方法
// Source: Eli Grey @ https://eligrey.com/blog/post/textcontent-in-ie8if ( Object.defineProperty && Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(Element.prototype, "textContent") && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) { (function () { var innerText = Object.getOwnPropertyDescriptor( Element.prototype, "innerText", ); Object.defineProperty( Element.prototype, "textContent", // Passing innerText or innerText.get directly does not work, // wrapper function is required. { get: function () { return innerText.get.call(this); }, set: function (s) { return innerText.set.call(this, s); }, }, ); })();}规范
| Specification |
|---|
| DOM> # dom-node-textcontent> |