hh54188
hh54188

Reputation: 15626

How can I get all text node in document fragment?

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?

Upvotes: 5

Views: 3755

Answers (3)

vsync
vsync

Reputation: 130255

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

Upvotes: 0

Richrd
Richrd

Reputation: 7132

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

Upvotes: 1

kavun
kavun

Reputation: 3381

use textContent

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

Upvotes: 3

Related Questions