如何获取文档片段中的所有文本节点

How can I get all text node in document fragment?

本文关键字:节点 文本 片段 文档 何获取 获取      更新时间:2023-09-26

我得到用户选择的文本:

var selection = window.getSelection();
var selectRange = selection.getRangeAt(0);
var content = selectRange.cloneContents(); // DocumentFragment

如何获取DocumentFragment内容中的textNode

使用textContent

var selection = window.getSelection();
var selectRange = selection.getRangeAt(0);
var content = selectRange.cloneContents(); // DocumentFragment
var text = content.textContent;

筛选fragment.childNodes以获取文本节点:

const selection = window.getSelection();
const selectRange = selection.getRangeAt(0);
const fragment = selectRange.cloneContents(); // DocumentFragment
// Get the child nodes and filter them to only include text nodes
const textNodes = Array.from(fragment.childNodes).filter(child => child.nodeName === "#text");

结合一些技巧,很容易从任何容器节点(在本例中为片段)中提取文本节点。问题的片段部分与提取部分无关。

获取容器的所有子项,使用展开运算符将它们转换为"真正的"数组...以便可以使用filter。也可以跳过这部分,因为 HTMLCollection 确实支持forEach因此可以在其中填充一个空数组。

请注意,Node.TEXT_NODE 是 DOM 常量,用于3

// create a demo fragment with some HTML mix of text nodes & elements
var frag = document.createRange().createContextualFragment("<a>1</a> 2 <b>3</b> 4.");
// now the work begins: get only the text nodes from the fragment
var textNodes = [...frag.childNodes].filter(node => node.nodeType == Node.TEXT_NODE)
// print the text nodes as an array
console.log( textNodes.map(node => node.textContent) )