1. textContent :
该属性用于设置或返回所选节点及其所有后代的文本值。在设置 textContent 属性时,所有子节点都会被删除。它被包含指定字符串的单个文本节点替换。
句法 :
- 要设置节点的文本 -
node.textContent = 文本
- 返回节点的文本 -
node.textContent
2. innerText :
此属性还设置或返回所选节点及其所有后代的文本值。但是,使用以下示例显示了一些差异。
HTML
<!DOCTYPE html>
< html >
< head >
< title >
Differences between innerText and textContent.
</ title >
</ head >
< body >
< h3 >Differences between innerText & textContent.</ h3 >
< p id = "demo" > This element has extra spacing and contains
< span >a span element</ span >.</ p >
< button onclick = "getInnerText()" >Get innerText</ button >
< button onclick = "getTextContent()" >Get textContent</ button >
< p id = "demo" ></ p >
< script >
function getInnerText() {
alert(document.getElementById("demo").innerText)
}
function getTextContent() {
alert(document.getElementById("demo").textContent)
}
</ script >
</ body >
</ html >
|
[/ tabbyending]
输出:
在单击任何按钮之前:
点击innerText按钮后:
点击 textContent 按钮后:
innerText 属性返回不带间距的文本,textContent 属性返回带间距的文本。
innerText 之间的其他区别:
SL 号 | 内部文本 | 文本内容 |
---|---|---|
1. | 它返回节点中包含的可见文本。 | 它返回全文。 |
2. | 它对性能的要求更高,因为它需要布局信息才能返回结果。 | 它并没有那么重的性能,因为它不需要布局信息来返回结果。 |
3. | 它仅针对 HTMLElement 对象定义。 | 它是为所有 Node 对象定义的。 |
4. | IE9 及更早版本不支持此属性。 | Internet Explorer 8 和更早版本不支持此属性。 |
读者注意!现在不要停止学习。