Skip to content

Instantly share code, notes, and snippets.

@alexmacarthur
Last active July 6, 2021 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexmacarthur/1b3d5ce219e6db58298afee5cdbfc5c2 to your computer and use it in GitHub Desktop.
Save alexmacarthur/1b3d5ce219e6db58298afee5cdbfc5c2 to your computer and use it in GitHub Desktop.
Expand Text Nodes - Split HTML Text Content into Individual Text Nodes for Each Character
// Unless the characters are individually inserted, the text content of HTML is grouped together in
// only as many text nodes are necessary to contain it. For example, the following markup will have only two text nodes:
//
// <span>first text node!<strong>second text node!</strong></span>
//
// Sometimes, however, you might want each character of text to exist as SEPARATE text nodes. This will do that. As a
// result, the afforementioned markup will contain 33 text nodes, rather than only two.
const expandTextNodes = (element) => {
[...element.childNodes].forEach((child) => {
if (child.nodeValue) {
child.nodeValue.split("").forEach((c) => {
child.parentNode.insertBefore(document.createTextNode(c), child);
});
child.remove();
return;
}
expandTextNodes(child);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment