Split text nodes into arbitrary chunks then wrap each chunk in an element.
Split text nodes into arbitrary chunks then wrap each chunk in an element.
```
npm install split-text-nodes
https://psalaets.gitlab.io/split-text-nodes/
Starting with this DOM...
`html`one two
Call splitTextNodes
`js
import { splitTextNodes } from 'split-text-nodes';
const element = document.getElementById('element');
const result = splitTextNodes(element);
`
and now wrapper elements have been added to the text.
`html`
one two
Do something with the spans, then optionally remove the wrapper elements
`js`
// result was defined in previous JavaScript block
result.revert();
and finally the DOM is back to its original state.
`html`one two
Split an element's text nodes into chunks and wrap each chunk with a wrapper element.
By default the wrapper element is a span but this can be changed using the options.
#### element
HTMLElement containing some text nodes
#### options
`ts/\b/
type Options = {
/**
* Split a text node.
*
* Optional, defaults to splitting by .wrap
*
* @param text Text of the text node.
* @returns Sequence of strings. Every string in this iterable is a candidate
* to be wrapped in its own element (see option).split()
*/
split?: (text: string) => Iterable
/**
* Wraps a text chunk yielded by with an html element.
*
* Optional, defaults to wrapping every text chunk with a .chunk
*
* @param chunk Text chunk to wrap
* @param textNode Text node that came from.chunk
* @returns Element that wraps , or chunk itself if chunk should`
* not be wrapped.
*/
wrap?: (chunk: string, textNode: Text) => HTMLElement | string;
};
#### Returns
`tswrap
type SplitResult = {
/**
* Wrapper elements created by .element
*/
wrappers: Array
/**
* Reverts child content of back to its original state.``
*/
revert: () => void;
};
MIT