最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get all text node in document fragment? - Stack Overflow

programmeradmin0浏览0评论

I get the user selected text:

var selection = window.getSelection();
var selectRange = selection.getRangeAt(0);

var content = selectRange.cloneContents(); // DocumentFragment

How can I get the textNode in the DocumentFragment content?

I get the user selected text:

var selection = window.getSelection();
var selectRange = selection.getRangeAt(0);

var content = selectRange.cloneContents(); // DocumentFragment

How can I get the textNode in the DocumentFragment content?

Share Improve this question edited Mar 22, 2020 at 13:43 Richrd 7,1421 gold badge19 silver badges12 bronze badges asked Nov 10, 2013 at 2:32 hh54188hh54188 15.7k35 gold badges116 silver badges192 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

use textContent

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

Filter fragment.childNodes to get the text nodes:

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");

Combining some tricks it is easy to extract the text nodes out of any container node (in this case a fragment). The fragment part of the question is irrelevant to the extraction part.

Getting all the children of the container, converting them to a "real" Array using the spread operator ... so filter could be used to. Can also skip this part because HTMLCollection does support forEach so it's possible to fill an empty Array within that.

Note that Node.TEXT_NODE is a DOM constant for 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) )

发布评论

评论列表(0)

  1. 暂无评论