Text:wholeText 属性
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Text
接口的 wholeText
只读属性返回与该节点逻辑上相邻的所有 Text
节点的完整文本。文本按文档顺序进行拼接。这样就允许指定任意文本节点并将所有相邻文本作为一个字符串获取。
备注:
这类似于调用 Node.normalize()
之后读取文本值,但不会修改树。
值
包含连接文本的字符串。
示例
假设你的网页中有以下简单的段落:
html
<p>
徒步旅行很不错!
<strong>平淡无奇的选举报道!</strong>
然而,<a href="https://zh.wikipedia.org/wiki/缺席投票">投票</a
>是一件棘手的事情。
</p>
你决定不喜欢中间的句子,所以把它去掉了:
js
const paragraph = document.querySelector("p"); // 读取该段
paragraph.removeChild(paragraph.childNodes[1]); // 删除 strong 元素
现在你的结果是 “徒步旅行很不错!然而,投票是一件棘手的事情。",超链接前有两个节点:
- 包含字符串
"徒步旅行很不错!"
的Text
节点 - 第二个
Text
节点,包含字符串"然而,"
要同时获取这两个节点,你可以调用 paragraph.childNodes[0].wholeText
:
js
console.log(`'${paragraph.childNodes[0].wholeText}'`); // '徒步旅行很不错!然而, '
规范
Specification |
---|
DOM # ref-for-dom-text-wholetext① |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
wholeText |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
参见
- 所属的
Text
接口。