split-text-nodes

9.0.0 • Public • Published

split-text-nodes

Split text nodes into arbitrary chunks then wrap each chunk in an element.

Install

npm install split-text-nodes

Examples

https://psalaets.gitlab.io/split-text-nodes/

Usage

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>

API

splitTextNodes(element, options = {})

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

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;
};

Returns

type SplitResult = {
  /**
   * Wrapper elements created by `wrap`.
   */
  wrappers: Array<HTMLElement>;
  /**
   * Reverts child content of `element` back to its original state.
   */
  revert: () => void;
};

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i split-text-nodes

Weekly Downloads

3

Version

9.0.0

License

MIT

Unpacked Size

7.7 kB

Total Files

9

Last publish

Collaborators

  • psalaets