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...
<div id="element">one two</div>
Call splitTextNodes
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.
<div id="element">
<span>one</span><span> </span><span>two<span>
</div>
Do something with the spans, then optionally remove the wrapper elements
// result was defined in previous JavaScript block
result.revert();
and finally the DOM is back to its original state.
<div id="element">one two</div>
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.
HTMLElement
containing some text nodes
type Options = {
/**
* Split a text node.
*
* Optional, defaults to splitting by `/\b/`.
*
* @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 `wrap` option).
*/
split?: (text: string) => Iterable<string>;
/**
* Wraps a text chunk yielded by `split()` with an html element.
*
* Optional, defaults to wrapping every text chunk with a `<span>`.
*
* @param chunk Text chunk to wrap
* @param textNode Text node that `chunk` came from.
* @returns Element that wraps `chunk`, or `chunk` itself if `chunk` should
* not be wrapped.
*/
wrap?: (chunk: string, textNode: Text) => HTMLElement | string;
};
type SplitResult = {
/**
* Wrapper elements created by `wrap`.
*/
wrappers: Array<HTMLElement>;
/**
* Reverts child content of `element` back to its original state.
*/
revert: () => void;
};
MIT